diff --git a/.gitignore b/.gitignore index b6dcdf70f031c6fa6b5a483e410f559ae145b1ba..39893782eeb8439bdf33ab6abe6ec497f3487c64 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,6 @@ output/ .env .env.* !.env.example + +# Host service dependencies for local tests (the image installs its own) +host/server/node_modules/ diff --git a/DETAILS.md b/DETAILS.md index 7c2187d0b9ab581e57641662349b5d7711ed9e53..7a98b079097f5845833145e39f18549976608ff0 100644 --- a/DETAILS.md +++ b/DETAILS.md @@ -34,3 +34,10 @@ - `docs/AI-INSTALL*.md`:供 AI 执行的部署、配置与验收指南 / AI deployment, configuration and verification guide. - `mac/clients/desktop/local-services.mjs`:置顶与分组的原 Host 设置适配、账户缓存恢复。 / Native Host settings for pins and groups, with account cache restoration. + +- `host/runtime/openai-chat.mjs`、`openai-responses.mjs`、`anthropic-messages.mjs`、`model-common.mjs`:三种模型接口格式的适配 / Adapters for the three model API formats. +- `host/runtime/reliability/tool-order.mjs`:一次模型回复中的消息按顺序送达 / Delivers the messages of one model response in order. +- `host/deploy.py`、`host/release/platforms.py`:部署、升级、备份恢复与架构检查 / Deployment, upgrades, backup and recovery, and architecture checks. +- `host/tools/host-admin.mjs`:命令行管理 / Command-line administration. +- `mac/clients/desktop/platform.mjs`:桌面客户端的平台差异 / Platform differences of the desktop client. +- `host/tests/`、`mac/tests/`、`ios/tests/`:测试,用 `node --test "host/tests/*.test.mjs"`、`node --test "mac/tests/*.test.mjs"` 运行 / Tests; run with `node --test "host/tests/*.test.mjs"` and `node --test "mac/tests/*.test.mjs"`. diff --git a/README.en.md b/README.en.md index 126f319bfad6ac778c98b422d0e59a3070c48a82..e06f21c9b699cde68c7a29a84e775b63b795e905 100644 --- a/README.en.md +++ b/README.en.md @@ -8,6 +8,8 @@ **A private server for Grok Bot.** Keep the original Grok Bot apps for Mac and iOS, and connect them to a server you host yourself. +For Windows or Android clients, use [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus), which is based on this project. +

macOS 0.71.2 iOS 1.16.0 @@ -17,7 +19,7 @@ [简体中文](README.md) · **English** -[Install](#install) · [Why](#why-i-built-this) · [Feature map](#how-the-original-features-are-provided) · [Under the hood](#how-each-part-was-built) · [Release notes](RELEASE.en.md) +[Install](#install) · [Why](#why-i-built-this) · [Feature map](#how-the-original-features-are-provided) · [Under the hood](#how-each-part-was-built) · [Compared with the official app](#compared-with-the-official-app) · [Server requirements](#server-requirements) · [Client versions](#client-versions) · [Release notes](RELEASE.en.md) The original Mac app connected to a self-hosted Host while an Agent operates a remote desktop @@ -67,7 +69,7 @@ The public edition provides Mac, iOS and Host patch tools. Supply the supported | --- | --- | --- | --- | | 🔁 Sign-in | Official account | The Host admin page creates a six-character pairing code; enter the Host address and code in the app to connect | — | | 🔁 Host and execution computer | Official cloud | Runs wherever you deploy it, using the original Host | Any device that can run Docker | -| 🔁 Chat models | Official models with automatic tier selection | You choose the models. The Jev classifier can pick the model and reasoning effort for each task | An OpenAI-compatible endpoint and API key | +| 🔁 Chat models | Official models with automatic tier selection | You choose the models. Add several model services and set the model, reasoning effort and backup models for all Bots or for one Bot | A model endpoint and API key: OpenAI Chat Completions, OpenAI Responses or Anthropic Messages | | 🟢 Computer and browser use | Original Agent | Kept as is | A model with vision | | 🟢 Memory, context compaction, scheduled tasks | Original Agent, partly backed by official services | Kept, now running on your models with local timers; compaction thresholds are configurable | — | | 🟢 Approvals, human takeover, input forms | Original | Kept as is | — | @@ -100,9 +102,14 @@ Disabled: virtual cards, external message drafts, product feedback and passkey f | **Usage** | See how many tokens you used each day, on the admin page and in the iOS settings. | | **Prompt management** | Edit system prompts and restore the original at any time, and see exactly which prompts and tools each role received. | | **Per-model context** | Set each model's context size and when summarization starts. | +| **Models per Bot** | Each Bot can have its own primary model, reasoning effort and backup models. If the primary fails before any output (quota, rate limit, service error, network), the backups are tried in order. | +| **Manual compaction** | Summarize an idle Bot's context from the admin page. | +| **Web client** | The Host can serve a web interface to browsers signed in with a pairing code. The bundle is built from the official Windows installer with the [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.en.md) tools and uploaded on the admin page; nothing changes until one is uploaded. | | **Admin page** | Configure everything in the browser. It follows the original design and supports Chinese and English, light and dark themes, and phone screens. | | **Split deployment** | Run the Host and the execution computer on different machines. | | **Backup and restore** | Back up all data and restore it as a new instance. | +| **Deploy tool** | `host/deploy.py` checks the environment, initializes, builds and starts, upgrades, backs up and restores, one command each. | +| **Command-line admin** | `host/tools/host-admin.mjs` sets up the Host, configures models and creates pairing codes without the web page. |

Host admin overview: five Bots working @@ -115,7 +122,7 @@ The tools read the supported original files, apply this project's changes, and g | Part | Implementation | | --- | --- | | **Host** | Reuses the original Host / Harness for task execution, tools, memory and context management. Adds administrator sign-in, pairing, providers and local scheduling. | -| **Models** | Converts requests to an OpenAI-compatible API. Choose a fixed model and reasoning effort, or enable Jev to route by task difficulty. | +| **Models** | Converts requests to OpenAI Chat Completions, OpenAI Responses or Anthropic Messages. The default route and Bot routes set the model, reasoning effort and backup order. A legacy configuration that routes by task difficulty with Jev keeps working, and saving it from the new model page asks for confirmation before migrating it. | | **Execution computer** | Runs the original Linux desktop image in Docker, together with the Host or on another machine. The Mac app connects to the Host to provide local operations and Codex coding. | | **Mac app** | Keeps the original Electron interface and replaces the connection and system integration main process. | | **iOS app** | Injects a dylib and applies fixed byte patches, keeping the interface, widgets, sharing and notification extensions. Sign the generated IPA yourself. | @@ -125,17 +132,72 @@ The tools read the supported original files, apply this project's changes, and g See [Features and architecture](docs/ARCHITECTURE.en.md) for more detail. +## Compared with the official app + +**Benefits** + +- Choose your own models and providers, billed through your own API; relays and aggregator gateways work too, and different Bots can use different models. +- Chats, files and memory stay on your own server, with no telemetry. +- Works where the official service isn't available, or only on your LAN. +- Some extras the official version doesn't have: editing the system prompt (the original can be restored at any time), context length per model, usage statistics, tasks triggered by webhooks, your own apps, Bot collaboration across several Hosts, and data backup and restore. + +**Trade-offs** + +- You need a machine that runs Docker, and you do upgrades and backups yourself. +- Versions are pinned: the Mac app at 0.71.2 and iOS at 1.16.0 (see [client versions](#client-versions)). When the official apps update, you have to wait for this project to support them; there are no automatic updates. +- Results depend on the model you choose. The official service is tuned for its own models, so other models may feel different. +- Some official features are turned off or replaced: virtual cards, external message drafts, product feedback and passkey forwarding are off; voice, push and image/video generation need providers you set up yourself; real-time voice calls are experimental. +- You sign the apps yourself: the Mac app is ad-hoc signed by default and needs your own certificate before a Bot can operate that Mac; on iPhone and iPad you sign and install with your own certificate. +- Modifying the official apps may violate the official terms of use. Use at your own risk. + +## Server requirements + +The models run at your API provider, so **the server needs no GPU**. It only runs two Docker containers: the Host and the execution computer (a Linux desktop). + +| | Minimum | Recommended | +| --- | --- | --- | +| CPU | 2 cores | 4 cores or more | +| Memory | 4 GB | 8 GB or more | +| Free disk space | 30 GB | 50 GB or more | +| System | A 64-bit system with Docker Engine 26+, Compose 2.26+ and Python 3.10+ | x86_64 Linux (tested on Ubuntu 24.04 with Docker 29) | + +This is enough for one person or a household. Heavy use by many people at once has not been tested. These figures come from [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus) test runs on x86_64 Linux: + +- **2 cores and 2 GB is not enough.** Both test runs failed to finish a series of chats in time, and the background model connection dropped and the core restarted. +- **2 cores / 4 GB and 4 cores / 8 GB both work.** Each was deployed from scratch and completed pairing, an attachment upload, several real chats and a cancellation; after a restart, chats and settings were all still there. A build from scratch takes about 9–10 minutes, depending on network speed. +- **Actual usage.** On a server with 6 cores and 16 GB, running for about a week, the Host used about 0.7 GB of memory (peak 0.9 GB) and the execution computer about 0.8 GB (peak 1.7 GB). The images take about 13 GB of disk. Chat and file data start under 100 MB and grow with use. +- The first deployment downloads the official files and base images from the internet, and the build needs extra temporary space. Backups also take space. + +| Your machines | Notes | +| --- | --- | +| One x86_64 Linux machine | **Recommended.** The Host and the execution computer run on the same machine; the figures above were measured this way. | +| ARM64 Linux + x86_64 Linux | The Host runs on the ARM machine and the execution computer on the x86_64 machine (the execution computer only exists for amd64). See [split deployment](host/docs/DEPLOYMENT.en.md). Chat and the remote desktop were tested on an Oracle Ampere A1 earlier; the current version has not been retested there. | +| ARM only (ARM64 Linux, Apple Silicon Mac) | The execution computer runs under emulation and is clearly slower; `python3 host/deploy.py doctor` checks whether it can run first. Docker Desktop on Apple Silicon Macs has not been tested. | +| A NAS | Anything that runs Docker Compose v2; match its CPU architecture to the rows above. Not tested. | + ## What you need | Item | Details | | --- | --- | -| **Machine** | A computer or NAS with Docker Compose. Images target Linux amd64; Apple Silicon Macs use emulation | +| **Machine** | A computer or NAS with Docker Compose; see [server requirements](#server-requirements). The Host image is built for the Docker machine's architecture (amd64 or arm64); the Linux desktop image is amd64 only and runs under emulation on ARM machines, including Apple Silicon Macs | | **Mac** | Apple Silicon Mac; supported client version: 0.71.2 | | **iOS** | The unsigned IPA from Releases, or your own decrypted 1.16.0 (23152) IPA; your own signing tools and certificate | | **Software** | Python 3.10+, Docker Compose; Node.js 22.12+ for Mac patching | -| **Required service** | An OpenAI-compatible model with tool calling; computer use needs image input | +| **Required service** | A model with tool calling, through OpenAI Chat Completions, OpenAI Responses or Anthropic Messages; computer use needs image input | | **Optional services** | Speech, media and search providers; Bark or your APNs credentials | +## Client versions + +The patches accept only the versions below and never update themselves. The latest official releases were checked on 2026-11-19; when they are newer than the right column, wait until this project supports them. + +| Platform | Latest official | Version this project needs | How to get it | +| --- | --- | --- | --- | +| macOS (Apple Silicon) | 1.2.3 | 0.71.2 | `mac/patchers/desktop/patch.mjs` downloads and verifies it | +| iOS / iPadOS | 1.26.0 | 1.16.0 (build 23152) | The IPA on the [releases page](https://gitee.com/ahaduoduoduo/ProkBot/releases); sign and install it yourself | +| Linux server | n/a | Host `d0a4baa`; execution computer `9d2ac1b` (amd64) | The build tools download and verify them | + +For the Windows and Android clients and the web client, see the versions in [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/README.en.md#client-versions). + ## Install Copy the following to an AI that can run commands, using the copy button at the top right of the code block: diff --git a/README.md b/README.md index 01bfbb8d304c7fafe1943c0b5ca4f1fa88d2d4de..1180697107f974a9460a2f8b1164f287799d2029 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ **一个 Grok Bot 私服。** 使用原版 Grok Bot 的 Mac 和 iOS 客户端,连接自部署服务端。 +需要 Windows 或 Android 客户端,请使用基于本项目的 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus)。 +

macOS 0.71.2 iOS 1.16.0 @@ -17,7 +19,7 @@ **简体中文** · [English](README.en.md) -[安装](#安装) · [为什么做这个](#为什么做这个) · [功能对照](#如何实现原生功能) · [实现思路](#每个部分是怎么做的) · [发布说明](RELEASE.md) +[安装](#安装) · [为什么做这个](#为什么做这个) · [功能对照](#如何实现原生功能) · [实现思路](#每个部分是怎么做的) · [和官方版比较](#和官方版比较) · [服务器要求](#服务器要求) · [客户端版本](#客户端版本) · [发布说明](RELEASE.md) 原版 Mac 客户端连接自建 Host,Agent 正在操作远程桌面 @@ -65,7 +67,7 @@ flowchart LR | --- | --- | --- | --- | | 🔁 登录 | 官方账号 | Host 管理页生成六位配对码,客户端输入 Host 地址和配对码即可连接 | — | | 🔁 Host 和执行电脑 | 官方云端 | 运行在你部署的位置,使用原版 Host | 一台能运行 Docker 的任意设备 | -| 🔁 对话模型 | 官方模型,自动选择等级 | 自行决定模型。可以让 Jev 分类器自动选择使用的模型和思考强度 | OpenAI 兼容接口的地址和 API Key | +| 🔁 对话模型 | 官方模型,自动选择等级 | 自行决定模型。可添加多个模型服务,给所有 Bot 或单个 Bot 指定模型、思考强度和备用模型 | 模型接口的地址和 API Key,支持 OpenAI Chat Completions、OpenAI Responses、Anthropic Messages | | 🟢 电脑和浏览器操作 | 原版 Agent | 保留原版 | 支持视觉能力的模型 | | 🟢 记忆、上下文压缩、定时任务 | 原版 Agent,部分依赖官方服务 | 保留原版,改用你的模型和本地计时,上下文压缩可自行设置 | — | | 🟢 操作审批、人工接管、交互表单 | 原版 | 保留原版 | — | @@ -98,9 +100,14 @@ flowchart LR | **用量统计** | 每天用了多少 Token,在管理页和 iOS 设置里都能看到。 | | **提示词管理** | 可以修改系统提示词并随时恢复原版,还能看到每个角色实际收到的提示词和工具。 | | **按模型设置上下文** | 每个模型的容量和开始摘要的时机可以单独设置。 | +| **按 Bot 选模型** | 每个 Bot 可以有自己的主模型、思考强度和备用模型。主模型还没输出时出错(额度、限流、服务故障、网络),按顺序换备用模型。 | +| **手动压缩上下文** | 在管理页把空闲 Bot 的上下文压缩成摘要。 | +| **网页版** | Host 可以向用配对码登录的浏览器提供网页版界面。界面包用 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.md) 的工具从官方 Windows 安装包生成,再在管理页上传;不上传就没有变化。 | | **管理网页** | 所有设置都在浏览器里完成,沿用原版的设计风格,支持中英文、深浅色和手机屏幕。 | | **分开部署** | Host 和执行电脑可以放在不同的机器上。 | | **备份恢复** | 备份全部数据,恢复成一个新的实例。 | +| **部署工具** | `host/deploy.py` 用一个命令完成环境检查、初始化、构建启动、升级、备份和恢复。 | +| **命令行管理** | `host/tools/host-admin.mjs` 不打开网页也能初始化、配置模型、生成配对码。 |

Host 管理页概览:5 个 Bot 正在工作 @@ -113,7 +120,7 @@ flowchart LR | 部分 | 实现方式 | | --- | --- | | **Host** | 复用原 Host / Harness 的任务执行、工具、记忆和上下文管理,补充管理员登录、设备配对、供应商配置与本地定时触发。 | -| **模型** | 将原模型请求转换为 OpenAI 兼容接口。可以固定模型和思考强度,也可以启用 Jev,按任务难度选择模型与强度。 | +| **模型** | 将原模型请求转换为 OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages 格式。默认路由和 Bot 路由指定模型、思考强度和备用顺序;使用 Jev 按任务难度选择的旧配置照常工作,在新模型页保存时会先确认再迁移。 | | **执行电脑** | 原 Linux 桌面镜像运行在 Docker 中,可以与 Host 分开部署。Mac 客户端主动连接 Host,提供本机操作与 Codex 编程。 | | **Mac 客户端** | 保留 Electron 原界面,替换连接和系统功能的主进程,接入自己的 Host。 | | **iOS 客户端** | 注入 dylib 并应用固定字节补丁,保留原界面、小组件、分享和通知扩展。输出的 IPA 自行签名安装。 | @@ -123,17 +130,72 @@ flowchart LR 更完整的说明见[功能与原理](docs/ARCHITECTURE.md)。 +## 和官方版比较 + +**好处** + +- 模型和服务商自己选,按你自己的接口计费,也可以用中转或聚合网关;不同的 Bot 可以用不同的模型。 +- 对话、文件、记忆都在自己的服务器上,没有遥测。 +- 官方服务用不了的地方也能用;只在局域网里用也行。 +- 多了一些官方没有的功能:修改系统提示词(随时能恢复原版)、按模型设置上下文长度、用量统计、Webhook 触发任务、自己写应用、多台 Host 之间的 Bot 协作、数据备份与恢复。 + +**代价** + +- 要有一台能运行 Docker 的机器,升级和备份要自己做。 +- 版本是固定的:Mac 客户端 0.71.2,iOS 1.16.0(见[客户端版本](#客户端版本))。官方出新版后,要等本项目适配才能升级,没有自动更新。 +- 效果取决于你选的模型。官方针对自家模型做过调校,换别的模型体验可能有差距。 +- 部分官方功能关掉或换掉了:虚拟卡、外部消息草稿、产品反馈、通行密钥转发已关闭;语音、推送、生图视频要自己准备服务商;实时语音通话还是实验功能。 +- 客户端要自己签名:Mac 客户端默认 ad-hoc 签名,想让 Bot 操作这台 Mac 需要用自己的证书签名;iPhone / iPad 用自己的证书签名安装。 +- 修改官方客户端可能违反官方用户条款,风险自负。 + +## 服务器要求 + +模型推理走 API,在模型服务商那边,**服务器不需要显卡**。服务器只运行两个 Docker 容器:Host 和执行电脑(Linux 桌面)。 + +| | 最低 | 推荐 | +| --- | --- | --- | +| CPU | 2 核 | 4 核或更多 | +| 内存 | 4 GB | 8 GB 或更多 | +| 硬盘可用空间 | 30 GB | 50 GB 或更多 | +| 系统 | 64 位系统,Docker Engine 26+ 和 Compose 2.26+,Python 3.10+ | x86_64 Linux(实测环境为 Ubuntu 24.04 + Docker 29) | + +这个配置适合一个人或一家人日常使用;多人同时高强度使用还没有测过。以下数据来自 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus) 在 x86_64 Linux 上的实测: + +- **2 核 2 GB 不够用。** 实测两次都没能按时完成连续对话,还出现过后台断连、核心重启。 +- **2 核 4 GB、4 核 8 GB 都实测可用。** 各自从零部署,完成了配对、上传附件、多轮真实对话、中途取消,重启后对话和设置都还在。从零构建大约要 9~10 分钟(视网速而定)。 +- **实际占用。** 一台 6 核 16 GB 的服务器连续运行约一周:Host 平时约 0.7 GB 内存,最高 0.9 GB;执行电脑平时约 0.8 GB,最高 1.7 GB。镜像约占 13 GB 硬盘,对话和文件数据刚开始不到 100 MB,会随使用增长。 +- 首次部署要从网上下载官方原版文件和基础镜像(国内网络可能需要代理),构建时还要额外的临时空间;备份也另占空间。 + +| 你的机器 | 说明 | +| --- | --- | +| 一台 x86_64 Linux | **推荐。** Host 和执行电脑装在同一台机器上,上面的数据都是这种方式测得的。 | +| ARM64 Linux + x86_64 Linux | Host 装在 ARM 机器上,执行电脑装在 x86_64 机器上(执行电脑只有 amd64 版本),见[分开部署](host/docs/DEPLOYMENT.md)。以往在甲骨文 Ampere A1 上测过对话和远程桌面,当前版本还没有重新测过。 | +| 只有 ARM 机器(ARM64 Linux、Apple Silicon Mac) | 执行电脑通过转译运行,明显更慢;`python3 host/deploy.py doctor` 会先检查能不能运行。Apple Silicon Mac 上的 Docker Desktop 没有测过。 | +| NAS | 能运行 Docker Compose v2 即可,按 CPU 架构对照上面几行;没有测过。 | + ## 你需要准备什么 | 类别 | 内容 | | --- | --- | -| **机器** | 支持 Docker Compose 的电脑或 NAS;镜像为 Linux amd64,Apple Silicon Mac 通过转译运行 | +| **机器** | 支持 Docker Compose 的电脑或 NAS,配置见[服务器要求](#服务器要求)。Host 镜像按 Docker 所在机器的架构构建(amd64 或 arm64);Linux 桌面镜像只有 amd64,在 ARM 机器(包括 Apple Silicon Mac)上通过转译运行 | | **Mac** | Apple Silicon Mac;支持的客户端版本为 0.71.2 | | **iOS** | 使用发布页提供的未签名 IPA,或自行注入 1.16.0(23152)砸壳包;准备自己的签名工具和证书 | | **软件** | Python 3.10+、Docker Compose;生成 Mac 客户端需要 Node.js 22.12+ | -| **必需服务** | 支持工具调用的 OpenAI 兼容模型接口;电脑操作需要模型支持图片输入 | +| **必需服务** | 支持工具调用的模型接口(OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages);电脑操作需要模型支持图片输入 | | **可选服务** | 语音、图片视频、搜索供应商;Bark 或自己的 APNs 凭据 | +## 客户端版本 + +补丁只认下面这些版本,不会自动更新。官方最新版是 2026-11-19 核对的,比右栏新时要等本项目适配。 + +| 平台 | 官方最新版 | 本项目需要的版本 | 怎么获得 | +| --- | --- | --- | --- | +| macOS(Apple Silicon) | 1.2.3 | 0.71.2 | `mac/patchers/desktop/patch.mjs` 自动下载并校验 | +| iOS / iPadOS | 1.26.0 | 1.16.0(构建 23152) | [发行页](https://gitee.com/ahaduoduoduo/ProkBot/releases)的 IPA,自行签名安装 | +| Linux 服务端 | 不适用 | Host `d0a4baa`;执行电脑 `9d2ac1b`(amd64) | 构建工具自动下载并校验 | + +Windows、Android 客户端和网页版的版本见 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus#client-versions)。 + ## 安装 复制下面内容给能执行命令的 AI,点击代码框右上角即可复制: diff --git a/docs/AI-INSTALL.en.md b/docs/AI-INSTALL.en.md index 75d4436b8167fc83e8fbf7bc010cbf4aa8155eb7..9b9733953b54fac5a6d4b5250bb922f1f33f1b33 100644 --- a/docs/AI-INSTALL.en.md +++ b/docs/AI-INSTALL.en.md @@ -4,9 +4,9 @@ Goal: deploy ProkBot, configure its model and connect the clients. Project: http ## Before starting -Ask together for: local or remote Host and working directory; Mac / iOS clients and local Mac control; LAN / Tailcat / existing HTTPS access; model endpoint, API key and model ID; and the administrator password for a new deployment. Remote deployment also needs connection details. +Ask together for: local or remote Host and working directory; Mac / iOS clients and local Mac control; LAN / Tailcat / existing HTTPS access; model API format (OpenAI Chat Completions, OpenAI Responses or Anthropic Messages), endpoint, API key and model ID; and the administrator password for a new deployment. Remote deployment also needs connection details. -Check architecture, memory, disk space and existing deployments. Reuse existing configuration and back up before updating. Install missing Python 3.10+ and Docker Compose. Mac patching runs on an Apple Silicon Mac with Node.js 22.12+. +Check architecture, memory, disk space and existing deployments. Reuse existing configuration and back up before updating. Install missing Python 3.10+, Docker Engine 26.0+ and Docker Compose 2.26.0+ (needed when the Host and Linux desktop share a machine; Ubuntu 24.04's own packages are enough). Mac patching runs on a Mac (Apple Silicon; Intel is experimental) with Node.js 22.12+. ## Inputs and outputs @@ -25,13 +25,18 @@ The example uses a new project named `prokbot`; reuse the project name and volum ```sh python3 host/release/build-docker.py +docker compose --env-file .env -p prokbot -f host/release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose --env-file .env -p prokbot -f host/release/compose.yaml up -d docker compose --env-file .env -p prokbot -f host/release/compose.yaml exec host cat /data/setup-key ``` -Images use Linux amd64; Docker on Apple Silicon uses emulation. For a separate Host and execution computer, select the Compose files described in `host/docs/DEPLOYMENT.en.md`. +The second command creates the memory and other directories the Linux desktop mounts, only where missing. Run it once before `up -d` for both new deployments and upgrades; otherwise the Linux desktop fails to start. -Open the administration page, initialize the administrator account, configure the user's model endpoint and key, select a model and test it. Configure and verify Tailcat under Remote Access when selected. +A new deployment can also use `doctor`, `init`, `up` and `status` from `python3 host/deploy.py` for the same steps; see `--help`. Existing deployments keep their current commands. + +The Host image is built for the Docker machine's architecture (amd64 or arm64). The Linux desktop image is amd64 only; on ARM machines Docker must run it under emulation, and the build tool checks this first. For a separate Host and execution computer, select the Compose files described in `host/docs/DEPLOYMENT.en.md`. + +Open the administration page and initialize the administrator account. Under Models, add a model service (API format, address, key), create a model profile (a service plus a model ID), set the default route, test each profile and save; if the user wants, give individual Bots their own primary model, reasoning effort and backup models. Configure and verify Tailcat under Remote Access when selected. Use the administration UI or consult `host/server/index.mjs` for the current request formats and sessions: diff --git a/docs/AI-INSTALL.md b/docs/AI-INSTALL.md index 5745534b3f4a217f127216252474938f1fd299ee..89f3fb7b42fc988756155ad5e4f436bbf5fe0e75 100644 --- a/docs/AI-INSTALL.md +++ b/docs/AI-INSTALL.md @@ -4,9 +4,9 @@ ## 开始前 -一次询问:Host 部署在本机还是远程机器及工作目录、需要 Mac / iOS 哪些客户端及是否控制 Mac、本机或远程的访问方式(局域网 / Tailcat / 已有 HTTPS)、模型接口地址 / API Key / 模型 ID,以及新部署的管理员密码。远程部署还需要连接方式。 +一次询问:Host 部署在本机还是远程机器及工作目录、需要 Mac / iOS 哪些客户端及是否控制 Mac、本机或远程的访问方式(局域网 / Tailcat / 已有 HTTPS)、模型接口格式(OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages)/ 地址 / API Key / 模型 ID,以及新部署的管理员密码。远程部署还需要连接方式。 -检查目标机器架构、内存、磁盘和已有部署;复用用户已有配置,更新前使用备份工具保存数据。安装缺少的 Python 3.10+、Docker Compose;Mac 补丁在 Apple Silicon Mac 上运行,需要 Node.js 22.12+。 +检查目标机器架构、内存、磁盘和已有部署;复用用户已有配置,更新前使用备份工具保存数据。安装缺少的 Python 3.10+、Docker Engine 26.0+ 和 Docker Compose 2.26.0+(Host 和 Linux 桌面同机部署时需要这些版本,Ubuntu 24.04 系统仓库的版本就够);Mac 补丁在 Mac 上运行(Apple Silicon;Intel 为实验支持),需要 Node.js 22.12+。 ## 资源与输出 @@ -25,13 +25,18 @@ ```sh python3 host/release/build-docker.py +docker compose --env-file .env -p prokbot -f host/release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose --env-file .env -p prokbot -f host/release/compose.yaml up -d docker compose --env-file .env -p prokbot -f host/release/compose.yaml exec host cat /data/setup-key ``` -镜像运行架构为 Linux amd64;Apple Silicon Docker 使用转译。Host 与 Linux 桌面可以分开部署,分开时按 `host/docs/DEPLOYMENT.md` 选择对应 Compose。 +第二条命令创建 Linux 桌面要挂载的记忆等目录,只建缺失的;新部署和升级后都要在 `up -d` 之前运行一次,否则 Linux 桌面启动失败。 -打开 Host 管理页,完成管理员初始化,填写用户的模型接口与 Key、选择模型并测试连接。需要 Tailcat 时,在「远程访问」配置并检查连接。 +新部署也可以用 `python3 host/deploy.py` 的 `doctor`、`init`、`up`、`status` 完成同样的步骤,选项见 `--help`;已有部署沿用原来的命令。 + +Host 镜像按 Docker 所在机器的架构构建(amd64 或 arm64);Linux 桌面镜像只有 amd64,在 ARM 机器上要靠 Docker 转译运行,构建工具会先检查能否运行。Host 与 Linux 桌面可以分开部署,分开时按 `host/docs/DEPLOYMENT.md` 选择对应 Compose。 + +打开 Host 管理页,完成管理员初始化。在「模型」里先添加模型服务(接口格式、地址、Key),再创建模型档案(服务 + 模型 ID),设置默认路由,逐个测试档案后保存;用户需要时再给单个 Bot 设置主模型、思考强度和备用模型。需要 Tailcat 时,在「远程访问」配置并检查连接。 可通过管理页操作,也可参考 `host/server/index.mjs` 的管理接口;请求格式与会话处理以该版本源码为准: diff --git a/docs/ARCHITECTURE.en.md b/docs/ARCHITECTURE.en.md index b419472307c6ce24041020e87f0994d3cedf6643..77a7da17f19f8a540a1c3e14a138751dfc9a4b8f 100644 --- a/docs/ARCHITECTURE.en.md +++ b/docs/ARCHITECTURE.en.md @@ -33,7 +33,7 @@ The project ships three patch tools. Together they let you build and run your ow | --- | --- | --- | --- | | 🔁 Sign-in | Official account | No account needed. The Host admin page creates a six-character pairing code; enter the Host address and code in the app to connect | — | | 🔁 Host and execution computer | Official cloud | Runs wherever you deploy it, using the original Host | Any device that can run Docker | -| 🔁 Chat models | Official models with automatic tier selection | You choose the models. The Jev classifier can pick the model and reasoning effort for each task | An OpenAI-compatible endpoint and API key | +| 🔁 Chat models | Official models with automatic tier selection | You choose the models. Add several model services and set the model, reasoning effort and backup models for all Bots or for one Bot | A model endpoint and API key: OpenAI Chat Completions, OpenAI Responses or Anthropic Messages | | 🟢 Computer and browser use | Original Agent | Kept as is | A model with vision | | 🟢 Memory, context compaction, scheduled tasks | Original Agent, partly backed by official services | Kept, now running on your models with local timers; compaction thresholds are configurable | — | | 🟢 Approvals, human takeover, input forms | Original | Kept as is | — | @@ -66,9 +66,14 @@ These original features aren't available yet: virtual cards, external message dr | **Usage** | See how many tokens you used each day, on the admin page and in the iOS settings. | | **Prompt management** | Edit system prompts and restore the original at any time, and see exactly which prompts and tools each role received. | | **Per-model context** | Set each model's context size and when summarization starts. | +| **Models per Bot** | Each Bot can have its own primary model, reasoning effort and backup models. If the primary fails before any output (quota, rate limit, service error, network), the backups are tried in order. | +| **Manual compaction** | Summarize an idle Bot's context from the admin page. | +| **Web client** | The Host can serve a web interface to browsers signed in with a pairing code. The bundle is built from the official Windows installer with the [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.en.md) tools and uploaded on the admin page; nothing changes until one is uploaded. | | **Admin page** | Configure everything in the browser. It follows the original design and supports Chinese and English, light and dark themes, and phone screens. | | **Split deployment** | Run the Host and the execution computer on different machines. | | **Backup and restore** | Back up all data and restore it as a new instance. | +| **Deploy tool** | `host/deploy.py` checks the environment, initializes, builds and starts, upgrades, backs up and restores, one command each. | +| **Command-line admin** | `host/tools/host-admin.mjs` sets up the Host, configures models and creates pairing codes without the web page. |
Host admin overview: five Bots working @@ -88,9 +93,13 @@ Around the original Host we wrote an admin service. It handles admin sign-in, de ### Models -The original sends model requests to an official classifier, which decides which model to use (Grok most of the time). We take over just before the Host sends a request, convert the original message format to the OpenAI-compatible format, and convert the streamed reply back. Tool calls, sub-Agents and context management are still the original logic. +The original sends model requests to an official classifier, which decides which model to use (Grok most of the time). We take over just before the Host sends a request, convert the original message format to the format you chose on the admin page (OpenAI Chat Completions, OpenAI Responses or Anthropic Messages), and convert the streamed reply back. Tool calls, sub-Agents and context management are still the original logic. -The original picks a model tier per task, and that decision happens on the official backend. Jev replaces it: it first judges how hard the task is, then hands it to the model for that tier. +When a provider rejects an optional parameter, the request is retried without it. Messages a Bot sends during one model response are delivered in the order the model wrote them. + +The original picks a model tier per task, and that decision happens on the official backend. Here you set it on the admin page instead: add model services (API format, address, key), then model profiles (a service plus a model ID). The default route applies to every Bot; a Bot can have its own primary model, reasoning effort and up to 8 backup models tried in order, and sub-Agents use their parent Bot's route. If the primary fails with 402, 408, 429, 5xx, a network error or an upstream idle timeout before it has produced any text or tool call, the next backup is tried; once output has started, the model is never switched, so replies and tool runs are not repeated. + +A configuration that used Jev to pick models by task difficulty keeps working after the upgrade; saving it from the new model page shows a notice and asks for confirmation before migrating it to per-Bot routes. A legacy single-model configuration that sets both a context size and a summary threshold now compacts automatically at that threshold. An idle Bot's context can also be compacted by hand on the admin page. ### Execution computer diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c3317cbbd60c04b39aa757ff9f0428682945af89..9af8e0c0c03cba5ebe07eae09ea56dd5ebfc9def 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,7 +33,7 @@ flowchart LR | --- | --- | --- | --- | | 🔁 登录 | 官方账号 | 不需要账号。Host 管理页生成六位配对码,客户端输入 Host 地址和配对码即可连接 | — | | 🔁 Host 和执行电脑 | 官方云端 | 运行在你部署的位置,使用原版 Host | 一台能运行 Docker 的任意设备 | -| 🔁 对话模型 | 官方模型,自动选择等级 | 自行决定模型。可以让 Jev 分类器自动选择使用的模型和思考强度 | OpenAI 兼容接口的地址和 API Key | +| 🔁 对话模型 | 官方模型,自动选择等级 | 自行决定模型。可添加多个模型服务,给所有 Bot 或单个 Bot 指定模型、思考强度和备用模型 | 模型接口的地址和 API Key,支持 OpenAI Chat Completions、OpenAI Responses、Anthropic Messages | | 🟢 电脑和浏览器操作 | 原版 Agent | 保留原版 | 支持视觉能力的模型 | | 🟢 记忆、上下文压缩、定时任务 | 原版 Agent,部分依赖官方服务 | 保留原版,改用你的模型和本地计时,上下文压缩可自行设置 | — | | 🟢 操作审批、人工接管、交互表单 | 原版 | 保留原版 | — | @@ -66,9 +66,14 @@ flowchart LR | **用量统计** | 每天用了多少 Token,在管理页和 iOS 设置里都能看到。 | | **提示词管理** | 可以修改系统提示词并随时恢复原版,还能看到每个角色实际收到的提示词和工具。 | | **按模型设置上下文** | 每个模型的容量和开始摘要的时机可以单独设置。 | +| **按 Bot 选模型** | 每个 Bot 可以有自己的主模型、思考强度和备用模型。主模型还没输出时出错(额度、限流、服务故障、网络),按顺序换备用模型。 | +| **手动压缩上下文** | 在管理页把空闲 Bot 的上下文压缩成摘要。 | +| **网页版** | Host 可以向用配对码登录的浏览器提供网页版界面。界面包用 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.md) 的工具从官方 Windows 安装包生成,再在管理页上传;不上传就没有变化。 | | **管理网页** | 所有设置都在浏览器里完成,沿用原版的设计风格,支持中英文、深浅色和手机屏幕。 | | **分开部署** | Host 和执行电脑可以放在不同的机器上。 | | **备份恢复** | 备份全部数据,恢复成一个新的实例。 | +| **部署工具** | `host/deploy.py` 用一个命令完成环境检查、初始化、构建启动、升级、备份和恢复。 | +| **命令行管理** | `host/tools/host-admin.mjs` 不打开网页也能初始化、配置模型、生成配对码。 |
Host 管理页概览:5 个 Bot 正在工作 @@ -88,9 +93,13 @@ flowchart LR ### 模型 -原版的模型请求发给官方分类器,由官方决定用哪个模型(大部分时间是 Grok)。我们在 Host 发出请求前接手,把原版的消息格式转换成 OpenAI 兼容格式,再把模型的流式回复转换回来。工具调用、子 Agent 和上下文管理仍然是原版逻辑。 +原版的模型请求发给官方分类器,由官方决定用哪个模型(大部分时间是 Grok)。我们在 Host 发出请求前接手,把原版的消息格式转换成你在管理页选择的格式(OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages),再把模型的流式回复转换回来。工具调用、子 Agent 和上下文管理仍然是原版逻辑。 -原版会按任务自动选择模型等级,这一步原本在官方后端完成。我们使用 Jev 来代替:先判断任务难度,再交给对应等级的模型。 +服务商不支持某个可选参数时,会去掉它再试一次。Bot 在一次模型回复里发出的几条消息,按模型写的顺序送达。 + +原版会按任务自动选择模型等级,这一步原本在官方后端完成。这里改成在管理页指定:先添加模型服务(接口格式、地址、Key),再创建模型档案(服务 + 模型 ID);默认路由用于所有 Bot,单个 Bot 可以另设主模型、思考强度和最多 8 个按顺序尝试的备用模型,子 Agent 沿用父 Bot 的路由。主模型还没输出文字或工具调用时,402、408、429、5xx、网络错误和上游空闲超时会换下一个备用模型;已经输出后不再切换,避免重复回复或重复执行工具。 + +之前用 Jev 按任务难度选择模型的配置升级后照常工作;在新的模型页保存时会先提示并确认,再迁移成按 Bot 路由。旧的单模型配置如果同时设置了上下文容量和摘要阈值,升级后会按这个阈值自动压缩。空闲的 Bot 也可以在管理页手动压缩上下文。 ### 执行电脑 diff --git a/docs/INSTALL.en.md b/docs/INSTALL.en.md index 0792d5dc74dba9faa321e87bc841d3eb05d482dc..c844ac45e01db5669b17880238244a2ef4e23f8c 100644 --- a/docs/INSTALL.en.md +++ b/docs/INSTALL.en.md @@ -4,12 +4,13 @@ ## 1. Deploy the Host -Requires Python 3.10+ and Docker Compose. The runtime is Linux amd64; Apple Silicon Macs use emulation. +Requires Python 3.10+, Docker Engine 26.0+ and Docker Compose 2.26.0+. The runtime is Linux amd64; Apple Silicon Macs use emulation. -From `host/` in the repository or extracted patch archive: +From `host/` in the repository or extracted patch archive (the second command creates the directories the Linux desktop mounts; run it again after upgrades): ```sh python3 release/build-docker.py +docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose -f release/compose.yaml up -d docker compose -f release/compose.yaml exec host cat /data/setup-key ``` @@ -20,7 +21,7 @@ Open `http://127.0.0.1:18080` and create an administrator account with the setup | App | Original input | Instructions | | --- | --- | --- | -| Mac | Automatically downloads Grok Bot 0.71.2 for Apple Silicon | [Patch the app](../mac/README.en.md) and move it into Applications | +| Mac | Automatically downloads Grok Bot 0.71.2 for the Mac's chip (Apple Silicon; Intel is experimental) | [Patch the app](../mac/README.en.md) and move it into Applications | | iOS | Decrypted Grok Bot 1.16.0 (23152), arm64 IPA including all three decrypted extensions | [Patch the IPA](../ios/README.en.md), then sign and install it | Open the app and enter the Host address and six-character pairing code. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index ba8d18049b519358447015cf22721ec7469c99c5..47b3abbca015b7563dd8b11252ee66a45692d28b 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -4,12 +4,13 @@ ## 1. 部署 Host -需要 Python 3.10+、Docker Compose,运行 Linux amd64 镜像。Apple Silicon Mac 使用转译运行。 +需要 Python 3.10+、Docker Engine 26.0+ 和 Docker Compose 2.26.0+,运行 Linux amd64 镜像。Apple Silicon Mac 使用转译运行。 -进入仓库或解压后的 `host/` 目录: +进入仓库或解压后的 `host/` 目录(第二条命令创建 Linux 桌面要挂载的目录,升级后也要再运行一次): ```sh python3 release/build-docker.py +docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose -f release/compose.yaml up -d docker compose -f release/compose.yaml exec host cat /data/setup-key ``` @@ -20,7 +21,7 @@ docker compose -f release/compose.yaml exec host cat /data/setup-key | 客户端 | 原文件 | 操作 | | --- | --- | --- | -| Mac | 工具自动下载 Grok Bot 0.71.2 Apple Silicon 原版 | 按 [Mac 说明](../mac/README.md)生成 App,移入「应用程序」 | +| Mac | 工具按本机芯片自动下载 Grok Bot 0.71.2 原版(Apple Silicon;Intel 为实验支持) | 按 [Mac 说明](../mac/README.md)生成 App,移入「应用程序」 | | iOS | Grok Bot 1.16.0(23152)arm64 砸壳 IPA,主应用及三个扩展均已解密 | 按 [iOS 说明](../ios/README.md)生成 IPA,自行签名安装 | 打开客户端,填写 Host 地址和六位配对码。 diff --git a/host/.dockerignore b/host/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..d7873fa4c018adf808b99373d4e5c4ad05d8bc06 --- /dev/null +++ b/host/.dockerignore @@ -0,0 +1,9 @@ +**/__pycache__/ +**/.cache/ +**/node_modules/ +**/output/ +**/inputs/ +**/backups/ +**/secrets/ +**/.env* +tests/ diff --git a/host/README.en.md b/host/README.en.md index 90bbbc958d78e4f5d13aa941d88f5a12b47313f5..60a71e92d4f8e4e20df737a3ab4fd3caad03ab8e 100644 --- a/host/README.en.md +++ b/host/README.en.md @@ -1,6 +1,6 @@ # ProkBot Host Patch -Self-host the Grok Bot server. Requires Python 3.10+ and Docker Compose; the runtime uses Linux amd64. +Self-host the Grok Bot server. Requires Python 3.10+, Docker Engine 26.0+ and Docker Compose 2.26.0+ (Ubuntu 24.04's own packages are enough). The Host image is built for the Docker machine's architecture (amd64 or arm64); the Linux desktop image is amd64. [简体中文](README.md) @@ -8,14 +8,37 @@ Self-host the Grok Bot server. Requires Python 3.10+ and Docker Compose; the run ```sh python3 release/build-docker.py +docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose -f release/compose.yaml up -d docker compose -f release/compose.yaml exec host cat /data/setup-key ``` Open `http://127.0.0.1:18080`, use the setup code to create an administrator account, configure a model and create a six-character pairing code. +The second command creates the memory and other directories the Linux desktop mounts from the data volume. It creates only missing ones and can be run again; without it the Linux desktop fails to start because a mount directory is missing. `deploy.py` does this step automatically. + For LAN access, run `export GROKBOT_LISTEN_ADDRESS=0.0.0.0` before starting Compose. +### Deploy tool + +`deploy.py` wraps the steps above, plus upgrades, backups and recovery, as subcommands. Instance settings (`.env` and backups) live in `~/grokbot` by default: + +```sh +python3 deploy.py doctor # check Docker, Compose, architecture and whether the Linux desktop can run +python3 deploy.py init # create .env; never overwrites an existing deployment +python3 deploy.py up # build and start a new deployment +python3 deploy.py status +python3 deploy.py setup-key # show the setup code +``` + +Use `update` to upgrade (it builds the new image first, then stops the old services, backs up and switches), `backup` to back up and `recover` to restore a backup as a new project. For a separate Host and Linux desktop, put `--host-only` before the subcommand. See `python3 deploy.py --help` for other options. + +`tools/host-admin.mjs` sets up the Host, configures models (all three API formats) and creates pairing codes from the command line; see `node tools/host-admin.mjs --help`. + +The admin page's Web client section accepts a web interface bundle; browsers can then sign in with a pairing code. The bundle is built from the official Windows installer with the [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.en.md) tools; nothing changes until one is uploaded. + +Tests: `node --test "tests/*.test.mjs"`. The web client route test needs `npm ci --prefix server --omit=dev --ignore-scripts` first; otherwise it is skipped. + [Remote access, separate deployment and backups](docs/DEPLOYMENT.en.md) · [Application development](PLUGINS.en.md) ## License and support diff --git a/host/README.md b/host/README.md index 436fb7298394807fe2edae321b2157ad1457d3e4..5747ee6c7e897bf6993313b486a5fd6917924a95 100644 --- a/host/README.md +++ b/host/README.md @@ -1,6 +1,6 @@ # ProkBot Host Patch -自建 Grok Bot 服务端。需要 Python 3.10+、Docker Compose,运行架构为 Linux amd64。 +自建 Grok Bot 服务端。需要 Python 3.10+、Docker Engine 26.0+ 和 Docker Compose 2.26.0+(Ubuntu 24.04 系统仓库的版本就够)。Host 镜像按 Docker 所在机器的架构构建(amd64 或 arm64),Linux 桌面镜像为 amd64。 [English](README.en.md) @@ -8,14 +8,37 @@ ```sh python3 release/build-docker.py +docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose -f release/compose.yaml up -d docker compose -f release/compose.yaml exec host cat /data/setup-key ``` 打开 `http://127.0.0.1:18080`,用初始化码设置管理员账号,配置模型并生成六位配对码。 +第二条命令在数据卷里创建 Linux 桌面要挂载的记忆等目录,只建缺失的,可以重复运行;不运行时 Linux 桌面会因为挂载目录不存在而启动失败。`deploy.py` 会自动做这一步。 + 需要局域网访问时,先设置 `export GROKBOT_LISTEN_ADDRESS=0.0.0.0`,再运行 Compose。 +### 部署工具 + +`deploy.py` 把上面的步骤以及升级、备份、恢复做成了子命令,实例配置(`.env` 和备份)默认放在 `~/grokbot`: + +```sh +python3 deploy.py doctor # 检查 Docker、Compose、架构,以及 Linux 桌面能否运行 +python3 deploy.py init # 生成 .env,不覆盖已有部署 +python3 deploy.py up # 构建并启动新部署 +python3 deploy.py status +python3 deploy.py setup-key # 显示初始化码 +``` + +升级用 `update`(先构建新镜像,再停止旧服务、备份并切换),备份用 `backup`,从备份恢复成新项目用 `recover`。Host 和 Linux 桌面分开部署时,在子命令前加 `--host-only`。其他选项见 `python3 deploy.py --help`。 + +`tools/host-admin.mjs` 可以在命令行初始化、配置模型(三种接口格式)和生成配对码,见 `node tools/host-admin.mjs --help`。 + +管理页的「网页版」可以上传网页版界面包,浏览器用配对码登录后就能使用。界面包用 [ProkBot Plus](https://github.com/ferretgeek/prokbot-plus/blob/main/web/README.md) 的工具从官方 Windows 安装包生成;不上传就没有变化。 + +运行测试:`node --test "tests/*.test.mjs"`。网页版路由测试需要先执行 `npm ci --prefix server --omit=dev --ignore-scripts`,否则跳过。 + [远程访问、分开部署与备份](docs/DEPLOYMENT.md) · [应用开发](PLUGINS.md) ## 许可与支持 diff --git a/host/bin/linux-arm64/grokbot-tailcat b/host/bin/linux-arm64/grokbot-tailcat new file mode 100755 index 0000000000000000000000000000000000000000..1a27779811640a4f185afd9bedc78d93e75de442 Binary files /dev/null and b/host/bin/linux-arm64/grokbot-tailcat differ diff --git a/host/deploy.py b/host/deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..ee578bb62ed0873fc92de6ecd9dab76d8936f80c --- /dev/null +++ b/host/deploy.py @@ -0,0 +1,574 @@ +#!/usr/bin/env python3 +"""Operate one local ProkBot Compose project, from a checkout or the Host release package.""" +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import ipaddress +import json +import os +from pathlib import Path +import posixpath +import re +import shutil +import subprocess +import sys +from urllib.parse import urlsplit +from uuid import uuid4 + +RELEASE = Path(__file__).resolve().parent / 'release' +MIN_DOCKER_ENGINE = (26, 0, 0) +MIN_DOCKER_API = (1, 45, 0) +MIN_COMPOSE = (2, 26, 0) +sys.path.insert(0, str(RELEASE)) +from platforms import BOX, check_box_execution, docker_platform +import backup as volume_backup + + +def run(cmd, *, env=None, capture=False): + return subprocess.run(cmd, env=env, stdin=subprocess.DEVNULL, check=True, text=True, + stdout=subprocess.PIPE if capture else None) + + +def endpoint(value): + url = urlsplit(value) + if (url.scheme not in ('https', 'http') or not url.hostname or url.username is not None or + url.password is not None or url.path not in ('', '/') or url.query or url.fragment or + not re.fullmatch(r'https?://[a-zA-Z0-9.\[\]:-]+/?', value) or url.port == 0): + raise ValueError('Public URL must be an HTTP(S) origin without credentials, a path, query or fragment.') + return value.rstrip('/') + + +def initialise(home, args): + if not 1 <= args.port <= 65535: + raise ValueError('Port must be 1..65535') + listen = str(ipaddress.ip_address(args.listen)) + if not args.public_url and listen != '127.0.0.1': + raise ValueError('Set --public-url to the address clients will actually enter.') + origin = endpoint(args.public_url or f'http://127.0.0.1:{args.port}') + if ':' in listen: + listen = f'[{listen}]' + # Only the local Box uses subpath mounts; a Host-only instance keeps working on older Docker. + if not args.host_only: + check_runtime_versions() + home.mkdir(mode=0o700, parents=True, exist_ok=True) + try: + fd = os.open(home / '.env', os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + raise ValueError('Configuration already exists; init never overwrites it. Use status or update.') from None + with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as config: + config.write(f'GROKBOT_LISTEN_ADDRESS={listen}\nGROKBOT_PUBLIC_PORT={args.port}\nGROKBOT_PUBLIC_URL={origin}\n' + f'PROKBOT_MODE={"remote" if args.host_only else "local"}\nPROKBOT_PROJECT={args.project}\n') + print(json.dumps({'configCreated': True, 'publicUrl': origin})) + + +def compose(args, home): + if not (home / '.env').is_file(): + raise ValueError('No .env in the instance directory. Run init first or select --home.') + name = 'compose.host.yaml' if args.host_only else 'compose.yaml' + return ['docker', 'compose', '--env-file', str(home / '.env'), '-p', args.project, '-f', str(RELEASE / name)] + + +def instance_settings(args, home): + # Only read the two markers written by init. Docker Compose interprets all other .env fields. + path = home / '.env' + markers = {} + if path.is_file(): + for line in path.read_text(encoding='utf-8').splitlines(): + key, _, value = line.partition('=') + if key in ('PROKBOT_MODE', 'PROKBOT_PROJECT'): + markers[key] = value.strip() + mode = markers.get('PROKBOT_MODE') + if mode not in (None, 'remote', 'local') or (mode == 'local' and args.host_only): + raise ValueError('Instance mode conflicts with its .env; do not switch topologies during an update.') + args.host_only = args.host_only or mode == 'remote' + saved = markers.get('PROKBOT_PROJECT') + if saved and args.project and saved != args.project: + raise ValueError('Project name conflicts with the instance .env; check --home and --project.') + args.project = args.project or saved or 'grokbot' + if not volume_backup.PROJECT_NAME.fullmatch(args.project): + raise ValueError('Invalid Compose project name') + + +def daemon_resources(): + info = json.loads(run(['docker', 'info', '--format', '{{json .}}'], capture=True).stdout) + report = {'cpuCount': info.get('NCPU'), 'memoryBytes': info.get('MemTotal')} + # Disk usage is local-only; a remote Docker context may use the same path on a different machine. + endpoint = os.environ.get('DOCKER_HOST') or run(['docker', 'context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'], capture=True).stdout.strip() + root = info.get('DockerRootDir') + if root and endpoint.startswith('unix://') and sys.platform.startswith('linux'): + try: + report['dockerDiskFreeBytes'] = shutil.disk_usage(root).free + except OSError: + pass + return report + + +def backup(args, home, image, *, stopped=False): + stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') + dest = home / 'backups' / f'{args.project}-{stamp}' + volume_backup.backup(args.project, dest, image, stopped=stopped) + return dest + + +def volume_policy(existing, images=None): + # Explicit process environment takes precedence over a stale setting in an instance .env. + env = {**os.environ, 'PROKBOT_EXISTING_VOLUMES': 'true' if existing else 'false'} + for service, ref in (images or {}).items(): + env['GROKBOT_'+service.upper()+'_IMAGE'] = ref + return env + + +def compose_mounts(service, definition): + # These settings can introduce mounts not listed in service.volumes. + for key in ('volumes_from', 'configs', 'secrets', 'use_api_socket'): + if definition.get(key): + raise ValueError(f'Effective Compose {service}.{key} introduces unmanaged mounts.') + mounts = list(definition.get('volumes', [])) + tmpfs = definition.get('tmpfs', []) + if isinstance(tmpfs, str): + tmpfs = [tmpfs] + mounts.extend({'type': 'tmpfs', 'target': item.partition(':')[0]} for item in tmpfs) + + roots = set(volume_backup.MOUNTS[service].values()) + data_targets = set(volume_backup.BOX_DATA_TARGETS) if service == 'box' else set() + allowed = roots | data_targets + by_target = {} + for mount in mounts: + target = mount.get('target') + if not isinstance(target, str) or not target.startswith('/'): + raise ValueError(f'Effective Compose mount on {service} needs an absolute container target.') + dest = posixpath.normpath('/' + target.lstrip('/')) + if dest in by_target: + raise ValueError(f'Duplicate effective Compose mount on {service} at {dest}.') + if dest not in allowed and (mount.get('type') != 'tmpfs' or + any(posixpath.commonpath((root, dest)) in (root, dest) for root in allowed)): + raise ValueError(f'Unmanaged mount on {service} at {dest} would be omitted from the backup.') + by_target[dest] = mount + return by_target + + +def instance_images(dc, project, services, existing, pinned=None): + config = json.loads(run(dc + ['config', '--format', 'json'], env=volume_policy(existing, pinned), capture=True).stdout) + if set(config['services']) != set(services): + raise ValueError('Effective Compose services do not match the selected topology.') + for s in services: + mounts = compose_mounts(s, config['services'][s]) + for suffix, dest in volume_backup.MOUNTS[s].items(): + mount = mounts.get(dest, {}) + volume = config.get('volumes', {}).get(suffix, {}) + if (volume.get('name') != project+'_'+suffix or volume.get('external', False) is not existing or + mount.get('type') != 'volume' or mount.get('source') != suffix or + mount.get('target') != dest or mount.get('read_only') or (mount.get('volume') or {}).get('subpath')): + raise ValueError(f'Effective Compose mount {s}:{dest} does not select the root of the expected writable project volume.') + if s == 'box': + for target, tree in volume_backup.BOX_DATA_TARGETS.items(): + mount = mounts.get(target, {}) + subpath = (mount.get('volume') or {}).get('subpath') + if (mount.get('type') != 'volume' or mount.get('source') != 'host-data' or + mount.get('target') != target or mount.get('read_only') or + subpath != str(volume_backup.DATA_SOURCE_ROOT / tree)): + raise ValueError(f'Effective Compose mount box:{target} does not select the approved Host-data tree.') + images = {s: config['services'][s]['image'] for s in services} + if pinned is not None and images != pinned: + raise ValueError('Effective Compose configuration did not select the requested immutable images.') + if pinned is None and 'box' in images and images['box'] != BOX['localTag']: + raise ValueError('This deployment entry point only starts the verified desktop tag from the input manifest.') + return images + + +def build(args, image): + cmd = [sys.executable, str(RELEASE / 'build-docker.py'), '--image', image] + if args.host_only: + cmd.append('--host-only') + for flag, path in [('host-archive', args.host_archive), ('box-archive', args.box_archive)]: + if path is not None: + cmd.extend(['--' + flag, str(path.resolve(strict=True))]) + run(cmd) + + +def inventory(project, services, *, new): + volumes = volume_backup.project_volumes(project) + expected = {f'{project}_{suffix}' for s in services for suffix in volume_backup.MOUNTS[s]} + if new: + named = set(volume_backup.output('volume', 'ls', '-q').splitlines()) + if volumes or expected & named or volume_backup.project_ids(project): + raise ValueError('Instance or conflicting volume exists. Check the project and use update for an existing instance.') + return {} + if volumes != expected: + raise ValueError('Volume set does not match this topology; check the original project, --home and --host-only.') + volume_backup.verify_volumes(project, volumes) + containers = volume_backup.project_services(project, services, host_data=f'{project}_host-data' in volumes) + volume_backup.verify_users(volumes, containers) + return containers + + +def image_id(ref): + identity = run(['docker', 'image', 'inspect', '--format', '{{.Id}}', ref], capture=True).stdout.strip() + if not re.fullmatch(r'sha256:[0-9a-f]{64}', identity): + raise ValueError('Docker did not return a usable local image identity.') + return identity + + +def startup_images(services, host_id): + images = {'host': host_id} + if 'box' in services: + box = image_id(BOX['localTag']) + if box not in (BOX['manifestDigest'], BOX['configDigest']): + raise ValueError('Local desktop image does not match the pinned desktop digest.') + images['box'] = box + return images + + +def version_tuple(value, label): + # Distribution builds add suffixes, e.g. Ubuntu's Compose reports 2.40.3+ds1-0ubuntu1~24.04.1. + match = re.match(r'v?(\d+)\.(\d+)(?:\.(\d+))?(?![\d.])', value) + if not match: + raise ValueError(f'Docker did not report a usable {label} version.') + return tuple(int(part or 0) for part in match.groups()) + + +def require_version(actual, minimum, label): + if actual < minimum: + found = '.'.join(map(str, actual)) + required = '.'.join(map(str, minimum)) + raise ValueError(f'{label} {found} is too old; version {required} or newer is required for Host-data subpath mounts.') + + +def compose_version(): + version = run(['docker', 'compose', 'version', '--short'], capture=True).stdout.strip() + # Compose labels its own volumes with the plain number, which backup lineage checks expect. + return '.'.join(map(str, version_tuple(version, 'Compose'))) + + +def check_runtime_versions(): + try: + server = json.loads(run(['docker', 'version', '--format', '{{json .Server}}'], capture=True).stdout) + except json.JSONDecodeError as error: + raise ValueError('Docker did not report usable Engine version details.') from error + if not isinstance(server, dict): + raise ValueError('Docker Engine is unavailable; start it before configuring Host data mounts.') + engine = server.get('Version') + api = server.get('ApiVersion') + if not isinstance(engine, str) or not isinstance(api, str): + raise ValueError('Docker did not report both Engine and API versions.') + engine_version = version_tuple(engine, 'Engine') + api_version = version_tuple(api, 'API') + compose = compose_version() + compose_number = version_tuple(compose, 'Compose') + require_version(engine_version, MIN_DOCKER_ENGINE, 'Docker Engine') + require_version(api_version, MIN_DOCKER_API, 'Docker API') + require_version(compose_number, MIN_COMPOSE, 'Docker Compose') + return {'dockerEngineVersion': engine, 'dockerApiVersion': api, 'composeVersion': compose} + + +def ensure_host_data(project, image): + name = project+'_host-data' + if name not in set(volume_backup.output('volume', 'ls', '-q').splitlines()): + run(['docker', 'volume', 'create', + '--label', f'{volume_backup.PROJECT_LABEL}={project}', + '--label', f'{volume_backup.VOLUME_LABEL}=host-data', + '--label', f'{volume_backup.VERSION_LABEL}={compose_version()}', + name], capture=True) + labels = volume_backup.volume_labels(name) + if labels.get(volume_backup.PROJECT_LABEL) != project or labels.get(volume_backup.VOLUME_LABEL) != 'host-data': + raise ValueError('The Host data volume does not belong to the selected project.') + run(['docker', 'run', '--rm', '--pull=never', '--network', 'none', '--read-only', '--user', '0:0', + '--entrypoint', 'python3', '--mount', f'type=volume,src={name},dst=/data,volume-nocopy', image, + '/opt/grokbot/release/data_init.py', '/data/runtime/host-data']) + + +def up_and_wait(dc, project, services, images, *, existing): + instance_images(dc, project, services, existing, pinned=images) + if 'box' in services: + ensure_host_data(project, images['host']) + run(dc + ['up', '-d', '--pull', 'never', '--wait', '--wait-timeout', '180'], env=volume_policy(existing, images)) + current = inventory(project, services, new=False) + if (set(current) != set(services) or any(c['State']['Status'] != 'running' for c in current.values()) or + any(current[s]['Image'] != images[s] for s in services)): + raise ValueError('Compose finished but the running services do not match the verified deployment.') + + +def stop_failed_start(dc, project, services, existing, notice, error): + try: + run(dc + ['stop'], env=volume_policy(existing)) + current = volume_backup.project_services(project, services) + if any(c['State']['Status'] not in ('exited', 'created') for c in current.values()): + raise ValueError('some services remain active') + except (OSError, ValueError, subprocess.SubprocessError) as stop_error: + raise RuntimeError(notice + ' Service shutdown NOT confirmed: ' + str(stop_error)) from error + raise RuntimeError(notice + ' Project services are stopped. Cause: ' + str(error)) from error + + +def tag_state(tag): + if (not re.fullmatch(r'[a-z0-9][a-z0-9._:/-]*(?::[\w.-]+)?', tag, re.ASCII) or '@' in tag or + re.fullmatch(r'(?:sha256:)?[0-9a-f]{64}', tag)): + raise ValueError('Configured Host build target must be a local tag, not an ID, digest or pattern.') + if ':' not in tag.rsplit('/', 1)[-1]: + tag += ':latest' + # A successful, empty tag inventory means absent. Any inspect/daemon error is a hard failure. + rows = run(['docker', 'image', 'ls', '--no-trunc', '--format', '{{.ID}}', tag], capture=True).stdout.splitlines() + if not rows: + return None + if len(rows) != 1 or not re.fullmatch(r'sha256:[0-9a-f]{64}', rows[0]) or image_id(tag) != rows[0]: + raise ValueError('Host tag inventory changed or is ambiguous; refusing to switch.') + return rows[0] + + +def revert_tag(previous, candidate, tag): + try: + actual = tag_state(tag) + if actual == previous: + return + if actual != candidate: + raise ValueError('another image owns this tag; it was not modified') + try: + if previous is None: + run(['docker', 'image', 'rm', '--no-prune', tag]) + else: + run(['docker', 'image', 'tag', previous, tag]) + except (OSError, subprocess.SubprocessError): + pass # The acknowledgement can be lost after the operation succeeds. + if tag_state(tag) != previous: + raise ValueError('previous tag state could not be verified') + except (OSError, ValueError, subprocess.SubprocessError) as error: + raise RuntimeError('Host tag rollback NOT confirmed; inspect local image metadata before retrying.') from error + + +def publish_image(previous, candidate, tag): + if tag_state(tag) != previous: + raise ValueError('Configured Host tag changed since preflight; refusing to replace it.') + try: + run(['docker', 'image', 'tag', candidate, tag]) + if tag_state(tag) != candidate: + raise ValueError('Candidate tag was not installed.') + except (Exception, KeyboardInterrupt): + revert_tag(previous, candidate, tag) + raise + + +@contextmanager +def staged_host(args, services): + candidate = 'prokbot-upgrade:' + uuid4().hex + build(args, candidate) + try: + check_platform(candidate) + yield startup_images(services, image_id(candidate)) + finally: + try: + run(['docker', 'image', 'rm', '--no-prune', candidate], capture=True) + except (OSError, subprocess.SubprocessError): + print('Could not remove temporary image tag: '+candidate, file=sys.stderr) + + +def upgrade(args, home, dc, services, image, old, root, continuing): + def state(containers): + return {s: (c['Id'], c['Image'], c['State']['Status']) for s, c in containers.items()} + + if any(c['State']['Status'] == 'paused' for c in old.values()): + raise ValueError('A project service is paused; resolve its state before upgrading.') + if set(old) != set(services): + raise ValueError('Missing original service container; cannot establish previous image identities from volume-only data. Use recover with a matching backup.') + previous = old['host']['Image'] + public_before = tag_state(image) + if image_id(previous) != previous: + raise ValueError('Previous Host image identity is unavailable; refusing to switch.') + with staged_host(args, services) as images: + candidate_id = images['host'] + current = inventory(args.project, services, new=False) + if state(current) != state(old) or instance_images(dc, args.project, services, True)['host'] != image: + raise ValueError('The instance changed during the build; no service was switched.') + offline_only = volume_backup.check_lineage(root, args.project, continuing=continuing) + if offline_only: + print('An unknown detached Host copy exists: automatic recovery is blocked on this daemon. ' + 'If the candidate fails after takeover, use data-only restore into new offline volumes.', + file=sys.stderr, flush=True) + running = [old[s]['Id'] for s in services if s in old and old[s]['State']['Status'] == 'running'] + try: + for cid in running: # Stop Host first so no new desktop work is dispatched. + run(['docker', 'stop', cid]) + dest = backup(args, home, previous, stopped=True) + # Keep the old image locally addressable after Compose removes its last container. + recovery_image = f'prokbot-recovery:{args.project}-{previous[7:]}' + run(['docker', 'image', 'tag', previous, recovery_image]) + offline_only = volume_backup.check_lineage(root, args.project, continuing=continuing) + publish_image(public_before, candidate_id, image) + except (Exception, KeyboardInterrupt): + # Before Compose up, only the original containers have touched the data. + # A manual peer start during the snapshot must not trigger a second identity on rollback. + volume_backup.check_lineage(root, args.project, continuing=continuing) + failed = [] + for cid in reversed(running): + try: + run(['docker', 'start', cid]) + except (OSError, subprocess.SubprocessError): + failed.append(cid) + if failed: + raise RuntimeError('Could not resume original containers; inspect their status: '+', '.join(failed)) + raise + try: + up_and_wait(dc, args.project, services, images, existing=True) + except (Exception, KeyboardInterrupt) as error: + # A candidate may already have migrated data. Never restart the old image on those volumes. + action = (f'An unknown detached Host copy exists; automatic recovery is blocked on this daemon. ' + f'Use data-only restore from {dest} into new offline volumes. Do not start those volumes ' + 'until conflicting identities are resolved.' if offline_only else + f'Run recover --directory {dest} for a NEW project.') + notice = f'Upgrade failed. No automatic data rollback. {action} Previous Host: {recovery_image} ({previous}).' + try: + stop_failed_start(dc, args.project, services, True, notice, error) + finally: + revert_tag(public_before, candidate_id, image) + + +def check_platform(image): + actual = run(['docker', 'image', 'inspect', '--format', '{{.Os}}/{{.Architecture}}', image], capture=True).stdout.strip() + if actual != docker_platform(): + raise ValueError('Host image platform does not match the Docker server; refusing to start.') + + +def recover(args, home, dc, services): + source = args.directory.expanduser().resolve(strict=True) + manifest = volume_backup.read_manifest(source) + origin = manifest['project'] + if args.project == origin: + raise ValueError('Recovery requires a NEW project, never the source project.') + images = manifest.get('serviceImages') + if (not isinstance(images, dict) or set(images) != set(services) or + any(not isinstance(i, str) or not re.fullmatch(r'sha256:[0-9a-f]{64}', i) for i in images.values())): + # Backups from backup.py or an older deploy.py record no image IDs. Starting them would mean + # guessing which image wrote the data, so they get the data-only path with its exact command. + raise ValueError('Backup has no verified service image IDs for this topology, so it cannot be started ' + 'automatically; do not guess tags. Use data-only restore: python3 release/backup.py restore ' + f'--project --directory {source} --image , ' + 'then start that project only after confirming no other copy of this Host identity runs.') + suffixes = {n for s in services for n in volume_backup.MOUNTS[s]} + if {r.get('suffix') for r in manifest['volumes'] if isinstance(r, dict)} != suffixes: + raise ValueError('Backup volumes do not match the selected recovery topology.') + if any(image_id(i) != i for i in images.values()): + raise ValueError('One of the exact recovery images is unavailable locally.') + check_platform(images['host']) + instance_images(dc, args.project, services, True, pinned=images) + root = manifest.get('lineageRoot') + with volume_backup.project_lock(origin), volume_backup.lineage_lock(root): + volume_backup.check_lineage(root, args.project, original=origin) + inventory(args.project, services, new=True) + volume_backup.restore(source, args.project, images['host'], manifest=manifest) + volume_backup.check_lineage(root, args.project, original=origin) + inventory(args.project, services, new=False) + try: + up_and_wait(dc, args.project, services, images, existing=True) + except (Exception, KeyboardInterrupt) as error: + stop_failed_start(dc, args.project, services, True, 'Recovery start failed. Restored volumes retained; source unchanged.', error) + print(json.dumps({'recoveredProject': args.project, 'sourceProject': origin, 'serviceImages': images, 'servicesStarted': True})) + + +def operate(args, home, dc): + services = ('host',) if args.host_only else ('host', 'box') + if args.action == 'recover': + return recover(args, home, dc, services) + image = instance_images(dc, args.project, services, args.action != 'up')['host'] + current = inventory(args.project, services, new=args.action == 'up') + if args.action == 'backup': + return backup(args, home, current['host']['Image'] if 'host' in current else image) + root = volume_backup.local_lineage(args.project) if args.action == 'update' else args.project + # Builders also publish fixed shared base/desktop tags. One daemon-wide writer covers aliases and rollback. + with volume_backup.lineage_lock(root), volume_backup.operation_lock('prokbot-image-publication-lock'): + # Preserve the pre-stop fact through snapshot and rollback. This exception never applies + # to a stopped Host, a restored Host, or recovery into a new project. + continuing = False + if (args.action == 'update' and root == args.project and 'host' in current and + current['host']['State']['Status'] == 'running'): + labels = volume_backup.volume_labels(args.project+'_host-data') + continuing = (labels.get(volume_backup.PROJECT_LABEL) == args.project and + labels.get(volume_backup.VOLUME_LABEL) == 'host-data' and + volume_backup.RESTORE_LABEL not in labels and volume_backup.LINEAGE_LABEL not in labels and + volume_backup.compose_created(labels)) + volume_backup.check_lineage(root, args.project, fresh=args.action == 'up', continuing=continuing) + if args.action == 'update': + upgrade(args, home, dc, services, image, current, root, continuing) + else: + previous = tag_state(image) + with staged_host(args, services) as images: + inventory(args.project, services, new=True) + volume_backup.check_lineage(root, args.project, fresh=True) + publish_image(previous, images['host'], image) + try: + up_and_wait(dc, args.project, services, images, existing=False) + except (Exception, KeyboardInterrupt) as error: + try: + stop_failed_start(dc, args.project, services, False, 'Installation failed. No volumes were removed.', error) + finally: + revert_tag(previous, images['host'], image) + run(dc + ['ps']) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--home', type=Path, default=Path.home() / 'grokbot', help='Instance directory (.env, backups); default ~/grokbot') + parser.add_argument('--project', help='Compose project/volume prefix; default: saved project or grokbot') + parser.add_argument('--host-only', action='store_true', help='Use a separately deployed execution node') + sub = parser.add_subparsers(dest='action', required=True) + init = sub.add_parser('init', help='Create .env once; never overwrite an existing deployment') + init.add_argument('--listen', default='127.0.0.1'); init.add_argument('--port', type=int, default=18080) + init.add_argument('--public-url', help='URL entered on clients; no subpath') + recovery = sub.add_parser('recover', help='Restore and start a NEW project from verified volumes and recorded immutable images') + recovery.add_argument('--directory', required=True, type=Path, help='Backup directory containing manifest.json') + for cmd, help_text in [('doctor', 'Check Docker, Compose, architecture and desktop compatibility'), + ('up', 'Build verified inputs and start a new installation'), + ('update', 'Stage a build, stop existing services, back up and switch to the candidate'), + ('backup', 'Back up all project volumes'), ('status', 'Show container status'), + ('logs', 'Show recent Host logs'), ('setup-key', 'Show the private, first-use setup key')]: + command = sub.add_parser(cmd, help=help_text) + if cmd in ('up', 'update'): + command.add_argument('--host-archive', type=Path, help='Use a previously downloaded pinned Host archive') + command.add_argument('--box-archive', type=Path, help='Use a previously saved pinned desktop image') + admin = sub.add_parser('admin', help='Run the bundled admin CLI; pass secrets via environment only') + admin.add_argument('arguments', nargs=argparse.REMAINDER) + args = parser.parse_args(argv); home = args.home.expanduser().resolve() + instance_settings(args, home) + if args.action == 'init': + return initialise(home, args) + if args.action == 'doctor': + report = {'ok': False, 'project': args.project, 'existingConfig': (home / '.env').is_file()} + try: + platform = docker_platform() + report.update(hostPlatform=platform, **({} if args.host_only else check_runtime_versions()), + desktop='remote' if args.host_only else 'native' if platform == BOX['platform'] else 'emulated-amd64', + existingVolumes=sorted(volume_backup.project_volumes(args.project)), resources=daemon_resources()) + help_text = run(['docker', 'compose', 'up', '--help'], capture=True).stdout + if '--wait-timeout' not in help_text: + raise ValueError('This Compose version cannot wait for service health. Install a Compose v2 with up --wait-timeout.') + report['hostDataVolumes'] = run(['docker', 'volume', 'ls', '-q', '--filter', 'label=com.docker.compose.volume=host-data'], capture=True).stdout.splitlines() + if report['existingConfig']: + run(compose(args, home) + ['config', '--quiet']) + if not args.host_only: + check_box_execution(platform) + report['ok'] = True + except (OSError, ValueError, subprocess.SubprocessError) as error: + report['error'] = str(error) + print(json.dumps(report)) + if not report['ok']: + raise SystemExit(1) + return + if args.action in ('up', 'update', 'recover') and not args.host_only: + check_runtime_versions() + dc = compose(args, home) + if args.action in ('status', 'logs', 'setup-key'): + return run(dc + {'status': ['ps', '--all'], 'logs': ['logs', '--tail', '100', 'host'], + 'setup-key': ['exec', '-T', 'host', 'cat', '/data/setup-key']}[args.action]) + if args.action == 'admin': + env = {**os.environ, 'GROKBOT_URL': 'http://127.0.0.1:8000'} + flags = [arg for k in ('GROKBOT_URL', 'GROKBOT_ADMIN_PASSWORD', 'MODEL_API_KEY') if k in env for arg in ('-e', k)] + extra = args.arguments or ['help'] + if extra[0] == 'setup': + extra = [*extra, '--setup-key-file', '/data/setup-key'] + return run(dc + ['exec', '-T', *flags, 'host', '/exec-daemon/node', 'tools/host-admin.mjs', *extra], env=env) + with volume_backup.project_lock(args.project): + return operate(args, home, dc) + + +if __name__ == '__main__': + try: + main() + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: + raise SystemExit(str(error)) from error diff --git a/host/deploy/healthcheck.mjs b/host/deploy/healthcheck.mjs index c8b9827accd7206998d231250465972d8f5adbad..4eb9835b56dc619094cae5980478a08b75a26c81 100644 --- a/host/deploy/healthcheck.mjs +++ b/host/deploy/healthcheck.mjs @@ -28,6 +28,17 @@ export async function checkDeploymentHealth(env = process.env) { !/^OPENAI_MODEL=.+$/m.test(model) ) return true; + // HostSupervisor intentionally waits for the execution node on split installations. + if (env.GROKBOT_REQUIRE_EXECUTION_NODE === '1') { + const state = await readFile(join(data, 'execution-node.json'), 'utf8').catch(error => { + if (error.code === 'ENOENT') return null; + throw error; + }); + if (state === null) return true; + const saved = JSON.parse(state); + if (saved?.version !== 1 || typeof saved.config?.enabled !== 'boolean') return false; + if (!saved.config.enabled) return true; + } const token = await internalCredential( env.GROKBOT_INTERNAL_HOST_TOKEN_FILE ?? join(data, "internal-host-token"), ); diff --git a/host/deploy/host-supervisor.mjs b/host/deploy/host-supervisor.mjs index 9fb40c5ae27277ec9846b1c05dee19d867902959..b51a0749e2581383f795d62f6ad0fcc98007ceec 100644 --- a/host/deploy/host-supervisor.mjs +++ b/host/deploy/host-supervisor.mjs @@ -156,7 +156,7 @@ export class HostSupervisor { !this.stopping ) { await this.status(revision, "waiting", "正在启动 Host"); - this.startHost(revision); + if (!this.stopping) this.startHost(revision); } return; } diff --git a/host/docs/DEPLOYMENT.en.md b/host/docs/DEPLOYMENT.en.md index 09703a16482b5e54cfa21097e4510e240eb4e6a3..a7cdb2c293a6b4e0a1c6e3d25138e03996727f60 100644 --- a/host/docs/DEPLOYMENT.en.md +++ b/host/docs/DEPLOYMENT.en.md @@ -1,9 +1,10 @@ # Deployment and backups -Requires Python 3.10+, Docker and Compose. The runtime uses Linux amd64. +Requires Python 3.10+, Docker Engine 26.0+ (API 1.45+) and Compose 2.26.0+; a standalone Host does not need these versions. Linux x86_64 and ARM64 are supported: the Host image is built for the Docker machine's architecture, and the Linux desktop image is amd64 only. On ARM machines, including Apple Silicon Macs, the desktop runs under emulation, and the build tool checks that it can run first. ```sh python3 release/build-docker.py --host-archive /path/to/sand-host-bundle-d0a4baa.tgz +docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose -f release/compose.yaml up -d docker compose -f release/compose.yaml exec host cat /data/setup-key ``` @@ -12,11 +13,14 @@ Open `http://127.0.0.1:18080`, initialize the administrator account, configure a Use `GROKBOT_LISTEN_ADDRESS=0.0.0.0` for LAN access and `GROKBOT_PUBLIC_PORT` for a different port. For remote access, use HTTPS or optional Tailcat. +The Linux desktop mounts only five directories from `host-data`: `agents`, `user-memory`, `workflows`, `plugins` and `managed-skills`, at `/data/runtime/host-data/`, the original Host path, so the Bot can read its memory on its own computer while the original path protection still applies and Read refuses `store.db`. `agent-transcripts`, `model.env`, `auth.json`, `connector-secrets` and `projects` stay out. Each directory is a `volume subpath`; older Compose may ignore the subpath and mount all of `host-data`, hence the minimum versions above, which `deploy.py` checks before writing or starting. `data_init.py` creates the directories (the second command above); it creates only missing ones and sets ownership only on those. + The `host-data`, `box-home` and `box-workspace` volumes retain data. The backup tool pauses running containers, saves all project volumes with checksums and resumes them. Restore into a new project without overwriting existing volumes: ```sh python3 release/backup.py backup --project grokbot --directory backups/2026-10-21 --image grokbot-host:local python3 release/backup.py restore --project grokbot-restored --directory backups/2026-10-21 --image grokbot-host:local +docker compose -p grokbot-restored -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose -p grokbot-restored -f release/compose.yaml up -d ``` diff --git a/host/docs/DEPLOYMENT.md b/host/docs/DEPLOYMENT.md index 762346808582bf33cf365ae3b4a2e1d6c221fe11..386160090dfc54db4316a5ec5e9d3b5535af362a 100644 --- a/host/docs/DEPLOYMENT.md +++ b/host/docs/DEPLOYMENT.md @@ -2,10 +2,11 @@ ## 构建 -需要 Python 3.10+、Docker 和 Compose。支持 Linux x86_64;Apple Silicon 可以构建 amd64 镜像。 +需要 Python 3.10+、Docker Engine 26.0+(API 1.45+)和 Compose 2.26.0+;只部署 Host 时不要求这些版本。支持 Linux x86_64 和 ARM64:Host 镜像按 Docker 所在机器的架构构建;Linux 桌面镜像只有 amd64,在 ARM 机器(包括 Apple Silicon Mac)上通过转译运行,构建工具会先检查能否运行。 ```sh python3 release/build-docker.py --host-archive /path/to/sand-host-bundle-d0a4baa.tgz +docker compose -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose -f release/compose.yaml up -d ``` @@ -21,11 +22,14 @@ docker compose -f release/compose.yaml exec host cat /data/setup-key ## 数据与更新 +Linux 桌面只挂载 `host-data` 里的 `agents`、`user-memory`、`workflows`、`plugins`、`managed-skills` 五个目录,位置是 `/data/runtime/host-data/<目录>`,和原版 Host 的路径一致,让 Bot 在自己的电脑上读记忆;原版的路径保护照样生效,Read 读不了 `store.db`。`agent-transcripts`、`model.env`、`auth.json`、`connector-secrets`、`projects` 不挂入。每个目录用一个 `volume subpath`,旧版 Compose 可能忽略子路径、把整个 `host-data` 挂进去,所以要求上面的最低版本,`deploy.py` 在写入或启动前检查。目录由 `data_init.py` 创建(见上面的第二条命令),它只建缺失的目录并设置这些新目录的属主,不改已有目录。 + Compose 持久保存 `host-data`、`box-home`、`box-workspace` 三个卷。备份工具暂停正在运行的容器,保存卷与摘要后恢复运行。恢复到一个新的 Compose 项目,不覆盖现有卷: ```sh python3 release/backup.py backup --project grokbot --directory backups/2026-10-21 --image grokbot-host:local python3 release/backup.py restore --project grokbot-restored --directory backups/2026-10-21 --image grokbot-host:local +docker compose -p grokbot-restored -f release/compose.yaml run --rm --no-deps --user 0:0 --entrypoint python3 host /opt/grokbot/release/data_init.py /data/runtime/host-data docker compose -p grokbot-restored -f release/compose.yaml up -d ``` diff --git a/host/network/build-tailcat.py b/host/network/build-tailcat.py index 776e6e193b160bd7e8eb8a24db6aa7f75207db97..08ec7249b1c3119322ff33cf14e7f2e0776e1d9c 100644 --- a/host/network/build-tailcat.py +++ b/host/network/build-tailcat.py @@ -7,7 +7,7 @@ import subprocess ROOT = Path(__file__).resolve().parents[1] parser = argparse.ArgumentParser(description=__doc__) -parser.add_argument('--target', choices=['native', 'linux-amd64', 'ios-arm64'], default='native') +parser.add_argument('--target', choices=['native', 'linux-amd64', 'linux-arm64', 'darwin-amd64', 'darwin-arm64', 'windows-amd64', 'ios-arm64'], default='native') parser.add_argument('--output', type=Path, default=ROOT / 'dist/network') args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=True) @@ -21,7 +21,14 @@ if args.target == 'ios-arm64': CGO_LDFLAGS=f'-arch arm64 -isysroot {sdk} -miphoneos-version-min=15.1') command += ['-buildmode=c-archive', '-o', str(args.output.resolve() / 'libGrokTailcat.a'), './mobile'] else: - if args.target == 'linux-amd64': - env.update(GOOS='linux', GOARCH='amd64', CGO_ENABLED='0') - command += ['-ldflags=-s -w', '-o', str(args.output.resolve() / 'grokbot-tailcat'), './cmd/grokbot-tailcat'] + name = 'grokbot-tailcat' + if args.target.startswith(('linux-', 'darwin-')): + goos, goarch = args.target.split('-') + env.update(GOOS=goos, GOARCH=goarch, CGO_ENABLED='0') + elif args.target == 'windows-amd64': + env.update(GOOS='windows', GOARCH='amd64', CGO_ENABLED='0') + name += '.exe' + elif args.target == 'native' and os.name == 'nt': + name += '.exe' + command += ['-ldflags=-s -w', '-o', str(args.output.resolve() / name), './cmd/grokbot-tailcat'] subprocess.run(command, cwd=ROOT / 'network/tailcat', env=env, check=True) diff --git a/host/recipes/host/manifest.json b/host/recipes/host/manifest.json index 5ff8cb554e47d2e2eb3dbe193b29a63d16aca613..a5bbec8cbff7d24ef63a7e0e2f2c98f1dcb6e92e 100644 --- a/host/recipes/host/manifest.json +++ b/host/recipes/host/manifest.json @@ -1,5 +1,16 @@ { "schema": "grokbot-host-inputs/v1", + "sourceSha256": { + "host-main.cjs": "d7ffb02b831337f6e4618a2604fb6ecd00a7f75f4c4bf96f5075f54d473b7f67", + "agent-isolation/agent-store-worker.cjs": "868572888c71b317c7878b5efc81b029aa99192e3bef7402591759388a6bcf3c" + }, + "box": { + "repository": "public.ecr.aws/k0i0n2g5/cursorenvironments/universal", + "platform": "linux/amd64", + "manifestDigest": "sha256:73c04dc8722de013fb2ad99366171e3a4c7379f1253d127348a5047d13f0ed41", + "configDigest": "sha256:1bdd316ac812b6647fe1163e97f200b99edb155b97d927727e85dc0c5ea3cd6f", + "localTag": "grokbot-box-input:9d2ac1b" + }, "archive": { "version": "d0a4baa", "url": "https://public-asphr-vm-daemon-bucket.s3.us-east-1.amazonaws.com/sand-host-bundle/sand-host-bundle-d0a4baa.tgz", diff --git a/host/recipes/host/recovered-core__stable__harness-provenance.json.gbp.gz b/host/recipes/host/recovered-core__stable__harness-provenance.json.gbp.gz index d55d3be0c15ff19ffa906cbbb2d5a9085b8422e1..e8687b2f97f3517767018ab82b8c11d4c5fdfd39 100644 Binary files a/host/recipes/host/recovered-core__stable__harness-provenance.json.gbp.gz and b/host/recipes/host/recovered-core__stable__harness-provenance.json.gbp.gz differ diff --git a/host/recipes/host/recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz b/host/recipes/host/recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz index 260db6f0d3591f1a827ee02674f46bbf0c954a72..2c1ccd81a376ca3af2ffd38c9f71cb4bc679136f 100644 Binary files a/host/recipes/host/recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz and b/host/recipes/host/recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz differ diff --git a/host/recipes/host/release-reliability__engine-tool-stream-executor.mjs.gbp.gz b/host/recipes/host/release-reliability__engine-tool-stream-executor.mjs.gbp.gz index b61aa2a1a48b7fc248c6dec06dc0ebc9c33f55c5..e3c348129e4d38e3d85a1ca720434c668a35e704 100644 Binary files a/host/recipes/host/release-reliability__engine-tool-stream-executor.mjs.gbp.gz and b/host/recipes/host/release-reliability__engine-tool-stream-executor.mjs.gbp.gz differ diff --git a/host/recipes/host/release-reliability__harness-provenance.json.gbp.gz b/host/recipes/host/release-reliability__harness-provenance.json.gbp.gz index d55d3be0c15ff19ffa906cbbb2d5a9085b8422e1..a9cb7f9795fc1d49b4ea4709f5c9512b6efeea3c 100644 Binary files a/host/recipes/host/release-reliability__harness-provenance.json.gbp.gz and b/host/recipes/host/release-reliability__harness-provenance.json.gbp.gz differ diff --git a/host/recipes/host/release-reliability__harness-turn-run-shell.mjs.gbp.gz b/host/recipes/host/release-reliability__harness-turn-run-shell.mjs.gbp.gz index f04ed2f295605e542582a3a705fa6d35539b45e8..3177b187f1ddb44be24d5eb89bc69affadacc67d 100644 Binary files a/host/recipes/host/release-reliability__harness-turn-run-shell.mjs.gbp.gz and b/host/recipes/host/release-reliability__harness-turn-run-shell.mjs.gbp.gz differ diff --git a/host/recipes/host/release-reliability__manifest.json.gbp.gz b/host/recipes/host/release-reliability__manifest.json.gbp.gz index 2c9ce3e0148439fb679c56b2514f1fbdea21f98a..2411d5509dc77885ad04560bb135ff6ea7528cd1 100644 Binary files a/host/recipes/host/release-reliability__manifest.json.gbp.gz and b/host/recipes/host/release-reliability__manifest.json.gbp.gz differ diff --git a/host/recipes/host/release-reliability__reliability.json.gbp.gz b/host/recipes/host/release-reliability__reliability.json.gbp.gz index 447a2e9a3c2577bb48878c8f3c7587eda0037a72..5d86239c615ab72196219c56f2130549162bc7e8 100644 Binary files a/host/recipes/host/release-reliability__reliability.json.gbp.gz and b/host/recipes/host/release-reliability__reliability.json.gbp.gz differ diff --git a/host/release/Dockerfile.arm-runtime b/host/release/Dockerfile.arm-runtime new file mode 100644 index 0000000000000000000000000000000000000000..9ab8d7af03d98a6acf48cfae7a1dd602a79c8599 --- /dev/null +++ b/host/release/Dockerfile.arm-runtime @@ -0,0 +1,11 @@ +FROM node:22-bookworm-slim AS addons +WORKDIR /addons +COPY release/arm-runtime/package*.json ./ +RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ && rm -rf /var/lib/apt/lists/* \ + && npm_config_nodedir=/usr/local npm ci --no-audit --no-fund + +FROM node:22-bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libfontconfig1 fonts-dejavu-core && rm -rf /var/lib/apt/lists/* \ + && mkdir -p /exec-daemon && ln -s /usr/local/bin/node /exec-daemon/node +COPY --from=addons /addons/node_modules/ /opt/sand/deps/ +RUN NODE_PATH=/opt/sand/deps /exec-daemon/node -e "const p=new (require('tree-sitter'))(); p.setLanguage(require('tree-sitter-bash')); if(p.parse('echo ok').rootNode.hasError) process.exit(1); const {CanvasElement}=require('@napi-rs/canvas-linux-arm64-gnu'); if(!new CanvasElement(8,8).toBuffer('image/png').length) process.exit(1)" diff --git a/host/release/Dockerfile.base b/host/release/Dockerfile.base index ce4d19839f1c6e17313c7b3a53ea6fe243729dfb..151ac8f0ee4c9d8d1ef2cf2828e82365fa0f90dd 100644 --- a/host/release/Dockerfile.base +++ b/host/release/Dockerfile.base @@ -5,11 +5,14 @@ COPY server/package*.json server/ RUN npm ci --prefix server --omit=dev --ignore-scripts --no-audit --no-fund COPY runtime/ runtime/ COPY server/ server/ +COPY tools/ tools/ COPY clients/shared/ clients/shared/ COPY deploy/ deploy/ COPY release/ release/ COPY recipes/ recipes/ COPY network/ network/ COPY bin/ bin/ +RUN case "$(dpkg --print-architecture)" in arm64) mv bin/linux-arm64/grokbot-tailcat bin/grokbot-tailcat ;; amd64) ;; *) exit 1 ;; esac \ + && rm -r bin/linux-arm64 && chmod 755 bin/grokbot-tailcat COPY THIRD_PARTY/ THIRD_PARTY/ # This stage contains only project code, delta recipes and open-source dependencies. diff --git a/host/release/Dockerfile.execution b/host/release/Dockerfile.execution index d3c89cacf230f9320d03eab4a41e5188d40425b6..8aee276b756c8d253ae89c7efefd59329125e9ad 100644 --- a/host/release/Dockerfile.execution +++ b/host/release/Dockerfile.execution @@ -3,6 +3,7 @@ WORKDIR /app COPY deploy/execution-gateway.mjs deploy/execution-tailcat.mjs deploy/ COPY clients/shared/ clients/shared/ COPY bin/grokbot-tailcat /app/bin/grokbot-tailcat +RUN chmod 755 /app/bin/grokbot-tailcat COPY network/TAILCAT-LICENSE /app/bin/TAILCAT-LICENSE COPY THIRD_PARTY/ /app/THIRD_PARTY/ ENV GROKBOT_TAILCAT_BINARY=/app/bin/grokbot-tailcat diff --git a/host/release/Dockerfile.host b/host/release/Dockerfile.host index 5e893f48acfdaefd038d05b7070a16659e9dd883..75f4ee56e1e17083b5dd0e96bf2cc674f046efd4 100644 --- a/host/release/Dockerfile.host +++ b/host/release/Dockerfile.host @@ -1,18 +1,19 @@ ARG PATCH_IMAGE=grokbot-patch-base:local -ARG BOX_IMAGE=public.ecr.aws/k0i0n2g5/cursorenvironments/universal@sha256:73c04dc8722de013fb2ad99366171e3a4c7379f1253d127348a5047d13f0ed41 +ARG RUNTIME_IMAGE=grokbot-box-input:9d2ac1b FROM ${PATCH_IMAGE} AS patch COPY inputs/host.tgz /inputs/host.tgz RUN python3 release/patch-host.py --archive /inputs/host.tgz --output /generated -FROM ${BOX_IMAGE} +FROM ${RUNTIME_IMAGE} +ARG HOST_REVISION WORKDIR /opt/grokbot COPY --from=patch /opt/grokbot /opt/grokbot -COPY --from=patch /generated/original artifacts/host-d0a4baa/sand-host/ +COPY --from=patch /generated/original artifacts/host-${HOST_REVISION}/sand-host/ COPY --from=patch /generated/seed seed/ -ENV NODE_PATH=/opt/sand/deps:/opt/sand/sand-host/node_modules:/exec-daemon/node_modules \ +ENV NODE_PATH=/opt/sand/deps:/opt/grokbot/artifacts/host-${HOST_REVISION}/sand-host/node_modules:/opt/sand/sand-host/node_modules:/exec-daemon/node_modules \ GROKBOT_DATA_DIR=/data GROKBOT_STATE_DIR=/data/runtime \ GROKBOT_MODEL_ENV=/data/model.env GROKBOT_HOST_DATA_DIR=/data/runtime/host-data \ - GROKBOT_ORIGINAL_HOST=/opt/grokbot/artifacts/host-d0a4baa/sand-host \ + GROKBOT_ORIGINAL_HOST=/opt/grokbot/artifacts/host-${HOST_REVISION}/sand-host \ GROKBOT_RUNTIME_DIR=/opt/grokbot/runtime GROKBOT_RECOVERED_CORE=1 \ GROKBOT_HOST_BIND=127.0.0.1 GROKBOT_HOST_PORT=1340 \ GROKBOT_INTERNAL_HOST_URL=http://127.0.0.1:1340 \ diff --git a/host/release/arm-runtime/package-lock.json b/host/release/arm-runtime/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..fc82520e36637f7b621554496c98bde737d1e1e2 --- /dev/null +++ b/host/release/arm-runtime/package-lock.json @@ -0,0 +1,83 @@ +{ + "name": "prokbot-arm-host-runtime", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "prokbot-arm-host-runtime", + "dependencies": { + "@napi-rs/canvas-linux-arm64-gnu": "0.1.80", + "tree-sitter": "0.25.0", + "tree-sitter-bash": "0.25.0" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-gnu": { + "version": "0.1.80", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.80.tgz", + "integrity": "sha512-qwA63t8A86bnxhuA/GwOkK3jvb+XTQaTiVML0vAWoHyoZYTjNs7BzoOONDgTnNtr8/yHrq64XXzUoLqDzU+Uuw==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "license": "MIT", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/tree-sitter": { + "version": "0.25.0", + "resolved": "https://registry.npmjs.org/tree-sitter/-/tree-sitter-0.25.0.tgz", + "integrity": "sha512-PGZZzFW63eElZJDe/b/R/LbsjDDYJa5UEjLZJB59RQsMX+fo0j54fqBPn1MGKav/QNa0JR0zBiVaikYDWCj5KQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-addon-api": "^8.3.0", + "node-gyp-build": "^4.8.4" + } + }, + "node_modules/tree-sitter-bash": { + "version": "0.25.0", + "resolved": "https://registry.npmjs.org/tree-sitter-bash/-/tree-sitter-bash-0.25.0.tgz", + "integrity": "sha512-gZtlj9+qFS81qKxpLfD6H0UssQ3QBc/F0nKkPsiFDyfQF2YBqYvglFJUzchrPpVhZe9kLZTrJ9n2J6lmka69Vg==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-addon-api": "^8.2.1", + "node-gyp-build": "^4.8.2" + }, + "peerDependencies": { + "tree-sitter": "^0.25.0" + }, + "peerDependenciesMeta": { + "tree-sitter": { + "optional": true + } + } + } + } +} diff --git a/host/release/arm-runtime/package.json b/host/release/arm-runtime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1fe8a110e8694d8ce5974667b324e8b69bda4594 --- /dev/null +++ b/host/release/arm-runtime/package.json @@ -0,0 +1,9 @@ +{ + "name": "prokbot-arm-host-runtime", + "private": true, + "dependencies": { + "@napi-rs/canvas-linux-arm64-gnu": "0.1.80", + "tree-sitter": "0.25.0", + "tree-sitter-bash": "0.25.0" + } +} diff --git a/host/release/backup.py b/host/release/backup.py index 7b404b217ea1e6b1b1c77cd43bee5a681a95c8a8..ec42b906d557dd359ed28fcfbc165f883558715e 100644 --- a/host/release/backup.py +++ b/host/release/backup.py @@ -1,23 +1,346 @@ #!/usr/bin/env python3 """Back up a Compose project's volumes, or restore them into a new project.""" import argparse +from contextlib import contextmanager import hashlib import json -from pathlib import Path +import os +from pathlib import Path, PurePosixPath import re import shutil import subprocess +import sys import time +from uuid import uuid4 DOCKER = shutil.which('docker') or '/usr/local/bin/docker' +PROJECT_NAME = re.compile(r'[a-z0-9][a-z0-9_-]{0,60}') +RESTORE_LABEL = 'io.prokbot.restore-id' +LINEAGE_LABEL = 'io.prokbot.lineage-root' +PROJECT_LABEL = 'com.docker.compose.project' +VOLUME_LABEL = 'com.docker.compose.volume' +VERSION_LABEL = 'com.docker.compose.version' +OPERATION_LABEL = 'io.prokbot.operation-id' +MOUNTS = {'host': {'host-data': '/data'}, 'box': {'box-home': '/home/box', 'box-workspace': '/workspace'}, + 'gateway': {'gateway-data': '/data'}} +TOPOLOGIES = (('host',), ('host', 'box'), ('gateway', 'box')) +DATA_TREES = ('agents', 'user-memory', 'workflows', 'plugins', 'managed-skills') +DATA_SOURCE_ROOT = PurePosixPath('runtime/host-data') +BOX_DATA_ROOTS = (PurePosixPath('/data/runtime/host-data'),) +BOX_DATA_TARGETS = {str(root / tree): tree for root in BOX_DATA_ROOTS for tree in DATA_TREES} def run(*args, **kwargs): + kwargs.setdefault('stdin', subprocess.DEVNULL) return subprocess.run([DOCKER, *args], check=True, **kwargs) def output(*args): - return subprocess.check_output([DOCKER, *args], text=True).strip() + return subprocess.check_output([DOCKER, *args], text=True, stdin=subprocess.DEVNULL).strip() + + +def project_volumes(project): + return set(output('volume', 'ls', '-q', '--filter', f'label=com.docker.compose.project={project}').splitlines()) + + +def topology(project, names): + for services in TOPOLOGIES: + if names == {f'{project}_{suffix}' for s in services for suffix in MOUNTS[s]}: + return services + raise ValueError('Incomplete or unexpected project volume set; check the original project and topology.') + + +def label_fields(field, keys): + fields = ','.join('"%s":{{json (index %s "%s")}}' % (k, field, k) for k in keys) + return '{{if '+field+'}}{'+fields+'}{{else}}{}{{end}}' + + +def volume_labels(name): + fmt = label_fields('.Labels', (PROJECT_LABEL, VOLUME_LABEL, VERSION_LABEL, RESTORE_LABEL, LINEAGE_LABEL, OPERATION_LABEL)) + labels = json.loads(output('volume', 'inspect', '--format', fmt, name)) + return {k: v for k, v in labels.items() if v} + + +@contextmanager +def operation_lock(name): + # The daemon's named-volume namespace is shared across homes, users and Docker clients. + # Never steal a stale lock: a disconnected updater may still be running. + token = uuid4().hex + try: + run('volume', 'create', '--label', f'{OPERATION_LABEL}={token}', name, stdout=subprocess.DEVNULL) + if volume_labels(name).get(OPERATION_LABEL) != token: + raise ValueError(f'Another operation owns {name}; do not remove an active lock.') + yield + finally: + try: + if name in output('volume', 'ls', '-q').splitlines() and volume_labels(name).get(OPERATION_LABEL) == token: + run('volume', 'rm', name, stdout=subprocess.DEVNULL) + except (OSError, ValueError, subprocess.SubprocessError) as error: + raise RuntimeError(f'Could not verify/release operation lock {name}; inspect before retrying.') from error + + +def project_lock(project): + if not PROJECT_NAME.fullmatch(project): + raise ValueError('Invalid Compose project name') + return operation_lock('prokbot-operation-'+project) + + +def lineage_lock(root): + if not isinstance(root, str) or not PROJECT_NAME.fullmatch(root): + raise ValueError('Unknown backup lineage; only offline data restore is safe.') + return operation_lock('prokbot-lineage-operation-'+root) + + +def compose_created(labels): + return re.fullmatch(r'v?\d+\.\d+(?:\.\d+)?(?:[-+][\w.+-]+)?', labels.get(VERSION_LABEL, '')) is not None + + +def volume_lineage(project, labels): + root = labels.get(LINEAGE_LABEL) + if root is not None and (not isinstance(root, str) or not PROJECT_NAME.fullmatch(root)): + raise ValueError('Invalid Host volume lineage metadata.') + # Legacy restored volumes have no proven source, even if this is the only copy on the daemon. + if root is None and RESTORE_LABEL not in labels and compose_created(labels): + root = project + return root + + +def volume_users(name): + return set(output('ps', '--all', '--no-trunc', '-q', '--filter', f'volume={name}').splitlines()) + + +def active_host_mount(name): + for c in inspect_containers(volume_users(name)): + if (c['State']['Status'] not in ('created', 'exited') and + (c['Labels'] or {}).get('com.docker.compose.service') == 'host' and + any(m['Type'] == 'volume' and m.get('Name') == name and m['Destination'] == '/data' for m in c['Mounts'])): + return True + return False + + +def host_volume_inventory(): + # No payloads, credentials, container environment, or client identity files are inspected. + names = set(output('volume', 'ls', '-q').splitlines()) + hosts = {n for n in names if n.endswith('_host-data')} + hosts.update(output('volume', 'ls', '-q', '--filter', f'label={VOLUME_LABEL}=host-data').splitlines()) + entries = {} + for name in hosts: + labels = volume_labels(name) + project = labels.get(PROJECT_LABEL, '') + role = labels.get(VOLUME_LABEL) + marked = RESTORE_LABEL in labels or LINEAGE_LABEL in labels + if not labels: + # Even the oldest managed restore set both Compose ownership labels. A suffix alone + # is not evidence of a copy; an actual Host /data mount or an exact target collision is. + if active_host_mount(name): + raise ValueError('A Host is using an unlabelled data volume; refusing activation.') + continue + if (not project and not role and not marked and re.fullmatch(r'[a-f0-9]{32}', labels.get(OPERATION_LABEL, '')) + and name.startswith(('prokbot-operation-', 'prokbot-lineage-operation-'))): + continue # A valid project name (and hence its lock name) can end in _host-data. + if (not marked and PROJECT_NAME.fullmatch(project) and role and compose_created(labels) and + (role != 'host-data' or name != project+'_host-data')): + continue # Explicit foreign Compose names are not managed ProkBot mounts. + if (not PROJECT_NAME.fullmatch(project) or name != project+'_host-data' or role != 'host-data'): + raise ValueError('Cannot establish lineage of an unmanaged Host volume on this daemon.') + entries[project] = (name, volume_lineage(project, labels)) + return entries + + +def local_lineage(project): + name = project+'_host-data' + if name not in project_volumes(project): + return None + labels = volume_labels(name) + if labels.get(PROJECT_LABEL) != project or labels.get(VOLUME_LABEL) != 'host-data': + raise ValueError('Host volume does not belong to the selected project.') + return volume_lineage(project, labels) + + +def check_lineage(root, project, *, original=None, fresh=False, continuing=False): + """Reject unsafe activation. Return whether detached unknown copies limited this approval.""" + if not isinstance(root, str) or not PROJECT_NAME.fullmatch(root): + raise ValueError('Unknown Host lineage; refusing automatic activation.') + entries = host_volume_inventory() + checked = set() + detached_unknown = False + for owner, (name, declared) in entries.items(): + if declared is None: + # Never activate an unknown copy. An empty install or the same already-running + # original may proceed past a different, detached copy; even stopped attachments count. + if ((fresh or continuing) and owner not in (root, project, original) and + not project_ids(owner) and not volume_users(name)): + detached_unknown = True + continue + raise ValueError('Unmarked legacy Host volume on this daemon; identity is ambiguous. Use offline data restore.') + if declared != root: + if owner in (root, project, original): + raise ValueError('Conflicting Host lineage; refusing activation.') + continue + if owner == project: + continue + peers = set(project_ids(owner)) + checked.update(peers | volume_users(name)) + for owner in {root, original} - {None, project}: + checked.update(project_ids(owner)) + for cid in checked: + if output('inspect', '--format', '{{.State.Status}}', cid) not in ('created', 'exited'): + raise ValueError('Another project with this Host identity is not stopped; refusing activation.') + return detached_unknown + + +def verify_volumes(project, names): + for name in names: + labels = volume_labels(name) + if (labels.get('com.docker.compose.project') != project or + labels.get('com.docker.compose.volume') != name[len(project)+1:]): + raise ValueError(f'Volume {name} does not have the expected project and volume labels.') + + +def project_ids(project): + return output('ps', '--all', '--no-trunc', '-q', '--filter', f'label=com.docker.compose.project={project}').splitlines() + + +def inspect_containers(ids): + # Request only lifecycle metadata, not a container's environment or other configuration. + labels = label_fields('.Config.Labels', (PROJECT_LABEL, 'com.docker.compose.service', 'com.docker.compose.oneoff')) + # Docker's resolved mount list omits VolumeOptions.Subpath. Project only the affected + # container destinations and source identities; never request HostConfig wholesale. + # `docker inspect` retries a template that fails on its typed structs against the raw JSON, + # with missing keys as errors; `.Id` and `index` on a struct fail there, so this template + # always reads the raw JSON. The daemon omits empty fields from it: HostConfig.Mounts on + # containers created with Binds (as Compose 2.40 does), VolumeOptions or Subpath on plain + # volume mounts. `index` reads such a key as empty instead of failing the inspection. + subpaths = ('[{{$sep := ""}}{{range index .HostConfig "Mounts"}}{{$target := index . "Target"}}' + '{{$source := index . "Source"}}{{with index . "VolumeOptions"}}' + '{{if index . "Subpath"}}{{$sep}}{"Target":{{json $target}},"Source":{{json $source}},' + '"Subpath":{{json (index . "Subpath")}}}{{$sep = ","}}{{end}}{{end}}{{end}}]') + fmt = ('{"Id":{{json .Id}},"Image":{{json .Image}},"State":{"Status":{{json .State.Status}}},' + '"Labels":'+labels+',"Declared":{{json (index .Config "Volumes")}},"Mounts":{{json .Mounts}},' + '"SubpathMounts":'+subpaths+'}') + records = [json.loads(line) for line in output('inspect', '--format', fmt, *ids).splitlines()] if ids else [] + if {c['Id'] for c in records} != set(ids): + raise ValueError('Container inventory changed during inspection.') + for record in records: + record['Mounts'] = record['Mounts'] or [] + record['SubpathMounts'] = record['SubpathMounts'] or [] + return records + + +def _under(path, root): + return path == root or path.is_relative_to(root) + + +def _data_source_tree(source, tree): + path = PurePosixPath(source or '') + expected = DATA_SOURCE_ROOT / tree + return path.is_absolute() and path.parts[-len(expected.parts):] == expected.parts + + +def _validate_box_data_mounts(c, project, *, host_data): + subpaths = {} + for item in c['SubpathMounts']: + target, source, subpath = item.get('Target'), item.get('Source'), item.get('Subpath') + if not isinstance(target, str) or not isinstance(source, str) or not isinstance(subpath, str): + raise ValueError('Box has an invalid subdirectory mount.') + if target in subpaths: + raise ValueError('Box has duplicate subdirectory mount metadata.') + subpaths[target] = (source, subpath) + + by_target = {} + for mount in c['Mounts']: + target = mount.get('Destination') + if target in BOX_DATA_TARGETS: + if target in by_target: + raise ValueError(f'Box has duplicate data mounts at {target}.') + by_target[target] = mount + + for mount in c['Mounts']: + target = PurePosixPath(mount.get('Destination', '')) + if any(_under(target, root) for root in BOX_DATA_ROOTS) and str(target) not in BOX_DATA_TARGETS: + raise ValueError(f'Box has an unapproved Host-data mount at {target}.') + for target in subpaths: + if target not in BOX_DATA_TARGETS: + raise ValueError(f'Box has an unmanaged subdirectory mount at {target}.') + + if not by_target and not subpaths: + return + if not host_data or set(by_target) != set(BOX_DATA_TARGETS): + raise ValueError('Box Host-data mounts are incomplete or do not belong to the local Host volume.') + + identities = {} + for target, tree in BOX_DATA_TARGETS.items(): + mount = by_target[target] + if mount.get('RW') is not True: + raise ValueError(f'Box Host-data mount at {target} is not writable.') + if mount.get('Type') == 'volume': + source = project+'_host-data' + expected = str(DATA_SOURCE_ROOT / tree) + if mount.get('Name') != source or subpaths.get(target) != (source, expected): + raise ValueError(f'Box volume mount at {target} does not select the expected Host-data tree.') + identities[target] = ('volume', source, expected) + elif mount.get('Type') == 'bind': + source = mount.get('Source') + if target in subpaths or not _data_source_tree(source, tree): + raise ValueError(f'Box bind mount at {target} does not select the expected Host-data tree.') + identities[target] = ('bind', source) + else: + raise ValueError(f'Box Host-data mount at {target} has an unsupported type.') + + for root in BOX_DATA_ROOTS: + for tree in DATA_TREES: + first = identities[str(root / tree)] + for other in BOX_DATA_ROOTS: + if identities[str(other / tree)] != first: + raise ValueError(f'Box exposes different sources for Host-data tree {tree}.') + + +def project_services(project, services, *, host_data=None): + result = {} + if host_data is None: + host_data = project+'_host-data' in project_volumes(project) + for c in inspect_containers(project_ids(project)): + labels = c['Labels'] or {} + service = labels.get('com.docker.compose.service') + if (labels.get('com.docker.compose.project') != project or service not in services or service in result or + (labels.get('com.docker.compose.oneoff') or '').lower() == 'true'): + raise ValueError('Unexpected or duplicate project container. Resolve it before operating on the instance.') + roots = {PurePosixPath(dest) for dest in MOUNTS[service].values()} + if any(str(PurePosixPath(item.get('Target', ''))) in MOUNTS[service].values() for item in c['SubpathMounts']): + raise ValueError(f'{service} uses a subdirectory instead of the managed volume root; refusing this operation.') + if service == 'box': + _validate_box_data_mounts(c, project, host_data=host_data) + elif c['SubpathMounts']: + raise ValueError(f'{service} has an unmanaged subdirectory mount; refusing this operation.') + box_data = set(BOX_DATA_TARGETS) if service == 'box' else set() + for mount in c['Mounts']: + dest = PurePosixPath(mount['Destination']) + if dest in roots or str(dest) in box_data: + continue + if service == 'box' and any(_under(dest, root) for root in BOX_DATA_ROOTS): + raise ValueError(f'Unmanaged Host-data mount on box at {dest}; refusing this operation.') + # Inherited image VOLUMEs may create anonymous scratch space outside managed data. + anonymous = (mount['Type'] == 'volume' and re.fullmatch(r'[0-9a-f]{64}', mount.get('Name', '')) and + str(dest) in (c.get('Declared') or {})) + if (any(dest.is_relative_to(root) or root.is_relative_to(dest) for root in roots) or + (mount['Type'] != 'tmpfs' and not anonymous)): + raise ValueError(f'Unmanaged mount on {service} at {dest} would be omitted; refusing this operation.') + for suffix, dest in MOUNTS[service].items(): + mounts = [m for m in c['Mounts'] if m['Destination'] == dest] + if (len(mounts) != 1 or mounts[0]['Type'] != 'volume' or mounts[0].get('Name') != project+'_'+suffix + or mounts[0].get('RW') is not True): + raise ValueError(f'{service}: {dest} is not the expected writable project volume.') + if c['State']['Status'] not in ('running', 'paused', 'exited', 'created'): + raise ValueError(f'{service} is in a transient or unsupported state; check docker ps before retrying.') + result[service] = c + return result + + +def verify_users(volumes, containers): + ids = {c['Id'] for c in containers.values()} + for name in volumes: + if volume_users(name) - ids: + raise ValueError(f'Another container uses {name}; detach it before taking a project snapshot.') def sha(path): @@ -28,60 +351,153 @@ def sha(path): return result.hexdigest() -def backup(project, destination, image): +def backup(project, destination, image, *, stopped=False): if destination.exists(): raise ValueError('Backup destination exists') - volumes = output('volume', 'ls', '--filter', f'label=com.docker.compose.project={project}', '--format', '{{.Name}}').splitlines() - if not volumes: - raise ValueError('No named Compose volumes found') - running = output('ps', '--filter', f'label=com.docker.compose.project={project}', '--filter', 'status=running', '--format', '{{.ID}}').splitlines() + volumes = project_volumes(project) + services = topology(project, volumes) + verify_volumes(project, volumes) + root = local_lineage(project) if 'host' in services else None + containers = project_services(project, services, host_data=project+'_host-data' in volumes) + verify_users(volumes, containers) + if stopped and any(c['State']['Status'] not in ('created', 'exited') for c in containers.values()): + raise ValueError('Upgrade backup requires all project containers to remain stopped.') destination.mkdir(parents=True, mode=0o700) paused = [] records = [] try: - for container in running: - if output('inspect', container, '--format', '{{.State.Paused}}') == 'false': - run('pause', container, stdout=subprocess.DEVNULL) - paused.append(container) - for volume in volumes: - if not volume.startswith(project+'_') or not re.fullmatch(r'[A-Za-z0-9_.-]+', volume): - raise ValueError('Unexpected volume name') + for c in containers.values(): + if c['State']['Status'] == 'running': + paused.append(c['Id']) # A failed CLI response does not prove the daemon did not pause it. + run('pause', c['Id'], stdout=subprocess.DEVNULL) + for volume in sorted(volumes): path = destination / (volume+'.tar.gz') with path.open('wb') as target: - run('run', '--rm', '--network', 'none', '--read-only', '--entrypoint', 'tar', '-v', volume+':/backup:ro', image, + run('run', '--rm', '--pull=never', '--network', 'none', '--read-only', '--user', '0:0', '--entrypoint', 'tar', + '--mount', f'type=volume,src={volume},dst=/backup,readonly,volume-nocopy', image, '-czf', '-', '-C', '/backup', '.', stdout=target) + os.fsync(target.fileno()) path.chmod(0o600) records.append({'name': volume, 'suffix': volume[len(project)+1:], 'file': path.name, 'sha256': sha(path), 'bytes': path.stat().st_size}) + current = project_services(project, services, host_data=project+'_host-data' in volumes) + expected = {c['Id']: 'paused' if c['Id'] in paused else c['State']['Status'] for c in containers.values()} + if project_volumes(project) != volumes or {c['Id']: c['State']['Status'] for c in current.values()} != expected: + raise ValueError('Instance changed during backup; no manifest was published.') + verify_users(volumes, current) finally: - for container in paused: - run('unpause', container, stdout=subprocess.DEVNULL) + failed = [] + for container in reversed(paused): + try: + status = output('inspect', '--format', '{{.State.Status}}', container) + if status == 'paused': + run('unpause', container, stdout=subprocess.DEVNULL) + elif status != 'running': + failed.append(container) + except (OSError, ValueError, subprocess.SubprocessError): + failed.append(container) + if failed: + raise RuntimeError('Could not resume these containers; check docker ps and unpause them: ' + ', '.join(failed)) manifest = {'schema':'grokbot-volumes/v1', 'project':project, 'image':image, + 'lineageRoot': root, + 'serviceImages': {s: c['Image'] for s, c in containers.items()}, 'at':time.strftime('%Y-%m-%dT%H:%M:%S%z'), 'volumes':records} - (destination/'manifest.json').write_text(json.dumps(manifest, indent=2)+'\n') - (destination/'manifest.json').chmod(0o600) + tmp = destination/'manifest.tmp' + with tmp.open('x', encoding='utf-8') as target: + target.write(json.dumps(manifest, indent=2)+'\n') + target.flush() + os.fsync(target.fileno()) + tmp.chmod(0o600) + tmp.replace(destination/'manifest.json') + if os.name == 'posix': + fd = os.open(destination, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(fd) + finally: + os.close(fd) print(json.dumps({'backup':str(destination), 'volumes':len(records), 'containersResumed':len(paused)})) -def restore(source, project, image): - manifest = json.loads((source/'manifest.json').read_text()) - if manifest.get('schema') != 'grokbot-volumes/v1': +def read_manifest(source): + manifest = json.loads((source/'manifest.json').read_text(encoding='utf-8')) + if not isinstance(manifest, dict) or manifest.get('schema') != 'grokbot-volumes/v1': raise ValueError('Unsupported backup format') + origin = manifest.get('project') + if not isinstance(origin, str) or not PROJECT_NAME.fullmatch(origin) or not isinstance(manifest.get('volumes'), list): + raise ValueError('Invalid backup manifest') + root = manifest.get('lineageRoot') + if root is not None and (not isinstance(root, str) or not PROJECT_NAME.fullmatch(root)): + raise ValueError('Invalid backup lineage metadata') + return manifest + + +def restore(source, project, image, *, manifest=None): + manifest = read_manifest(source) if manifest is None else manifest + origin = manifest['project'] prepared = [] + suffixes = set() for record in manifest['volumes']: - if not re.fullmatch(r'[A-Za-z0-9_.-]+', record['suffix']) or Path(record['file']).name != record['file']: - raise ValueError('Invalid backup filename') - path = source/record['file']; name = project+'_'+record['suffix'] - if sha(path) != record['sha256']: + suffix = record.get('suffix') if isinstance(record, dict) else None + if not isinstance(suffix, str) or not re.fullmatch(r'[a-z0-9-]+', suffix) or suffix in suffixes: + raise ValueError('Invalid or duplicate backup volume') + suffixes.add(suffix) + original = origin+'_'+suffix + if record.get('name') != original or record.get('file') != original+'.tar.gz': + raise ValueError('Backup filename does not match the recorded volume') + path = source/record['file']; name = project+'_'+suffix + if not path.is_file() or path.is_symlink() or path.stat().st_size != record.get('bytes') or sha(path) != record.get('sha256'): raise ValueError('Backup checksum mismatch: '+record['file']) - exists = subprocess.run([DOCKER, 'volume', 'inspect', name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 - if exists: - raise ValueError('Restore target already exists: '+name) - prepared.append((path, name, record['suffix'])) - for path, name, suffix in prepared: - run('volume','create','--label',f'com.docker.compose.project={project}','--label',f'com.docker.compose.volume={suffix}',name, stdout=subprocess.DEVNULL) - with path.open('rb') as source_file: - run('run','--rm','-i','--network','none','--read-only','--entrypoint','tar','-v',name+':/restore',image, - '-xzf','-','-C','/restore', stdin=source_file) + prepared.append((path, name, suffix)) + topology(origin, {origin+'_'+s for s in suffixes}) + targets = {n for _, n, _ in prepared} + if project_ids(project) or project_volumes(project) or targets.intersection(output('volume', 'ls', '-q').splitlines()): + raise ValueError('Restore target already exists; choose a new project.') + + # This extra project volume makes an interrupted restore fail every managed topology check. + claim = uuid4().hex + guard = project+'_restore-in-progress' + created = [] + + def reserve(name, suffix): + # docker volume create succeeds for an existing name, or may create one then lose the reply. + created.append(name) + root = manifest.get('lineageRoot') + lineage = ['--label', f'{LINEAGE_LABEL}={root}'] if root is not None else [] + run('volume', 'create', '--label', f'{RESTORE_LABEL}={claim}', '--label', f'com.docker.compose.project={project}', + '--label', f'com.docker.compose.volume={suffix}', *lineage, name, stdout=subprocess.DEVNULL) + if volume_labels(name).get(RESTORE_LABEL) != claim: + raise ValueError('Restore target was created concurrently: '+name) + + try: + reserve(guard, 'restore-in-progress') + for _, name, suffix in prepared: + reserve(name, suffix) + for path, name, _ in prepared: + if volume_labels(name).get(RESTORE_LABEL) != claim or project_ids(project): + raise ValueError('Restore target changed; refusing to write to '+name) + verify_users([name], {}) + with path.open('rb') as source_file: + run('run', '--rm', '-i', '--pull=never', '--network', 'none', '--read-only', '--user', '0:0', '--entrypoint', 'tar', + '--mount', f'type=volume,src={name},dst=/restore,volume-nocopy', image, '-xzf', '-', '-C', '/restore', stdin=source_file) + if project_ids(project) or project_volumes(project) != (targets | {guard}): + raise ValueError('Restore target changed during extraction.') + verify_users(targets, {}) + if any(volume_labels(name).get(RESTORE_LABEL) != claim for name in created): + raise ValueError('Restore ownership changed during extraction.') + run('volume', 'rm', guard, stdout=subprocess.DEVNULL) + except (Exception, KeyboardInterrupt): + failed = [] + for name in reversed(created): + if name == guard and failed: + failed.append(guard) + break + try: + if name in output('volume', 'ls', '-q').splitlines() and volume_labels(name).get(RESTORE_LABEL) == claim: + run('volume', 'rm', name, stdout=subprocess.DEVNULL) + except (OSError, ValueError, subprocess.SubprocessError): + failed.append(name) + if failed: + raise RuntimeError('Could not verify or clean partial restore volumes; do not start this project: '+', '.join(failed)) + raise print(json.dumps({'restoredProject':project,'volumes':len(prepared),'servicesStarted':False})) @@ -92,13 +508,17 @@ def main(): parser.add_argument('--directory',required=True,type=Path) parser.add_argument('--image',default='grokbot-host:local') args=parser.parse_args() - if not re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,60}',args.project): + if not PROJECT_NAME.fullmatch(args.project): parser.error('Invalid Compose project name') - if args.operation=='backup': - backup(args.project,args.directory,args.image) - else: - restore(args.directory,args.project,args.image) + with project_lock(args.project): + if args.operation=='backup': + backup(args.project,args.directory,args.image) + else: + restore(args.directory,args.project,args.image) if __name__=='__main__': - main() + try: + main() + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: + sys.exit(str(error)) diff --git a/host/release/build-docker.py b/host/release/build-docker.py index 7ae0f1cbbdcb7a539dda44fd0b4fbf036d8fc596..acec394c43592b53b8b6640f77b5e9836b82c71e 100644 --- a/host/release/build-docker.py +++ b/host/release/build-docker.py @@ -3,49 +3,95 @@ import argparse import hashlib import json +import re from pathlib import Path import shutil import subprocess +import tarfile import tempfile import time import urllib.request +from bytepatch import file_digest +from platforms import BOX as BOX_SPEC, INPUTS, check_box_execution, docker_platform ROOT = Path(__file__).resolve().parents[1] -BOX = 'public.ecr.aws/k0i0n2g5/cursorenvironments/universal@sha256:73c04dc8722de013fb2ad99366171e3a4c7379f1253d127348a5047d13f0ed41' -BOX_ID = 'sha256:1bdd316ac812b6647fe1163e97f200b99edb155b97d927727e85dc0c5ea3cd6f' +BOX = BOX_SPEC['repository'] + '@' + BOX_SPEC['manifestDigest'] +BOX_ID = BOX_SPEC['configDigest'] +BOX_MANIFEST = BOX.split('@', 1)[1] +# The classic image store reports the config digest as the image ID; the containerd +# image store (default on new Docker 29+ installs) reports the pinned manifest digest. +BOX_IDENTITIES = {BOX_ID, BOX_MANIFEST} +BOX_TAG = BOX_SPEC['localTag'] def run(*args, **kwargs): subprocess.run(args, check=True, **kwargs) +def image_id(reference): + probe = subprocess.run(['docker', 'image', 'inspect', reference, '--format', '{{.Id}}'], capture_output=True, text=True) + return probe.stdout.strip() if probe.returncode == 0 else None + + +def load_verified_archive(path): + """Verify a docker-save archive by its config digest, independent of the Docker image store.""" + with tarfile.open(path, 'r:*') as archive: + names = {member.name.lstrip('./'): member for member in archive} + entries = json.load(archive.extractfile(names['manifest.json'])) + if len(entries) != 1: + raise ValueError('Box archive must contain exactly one image') + config = archive.extractfile(names[entries[0]['Config'].lstrip('./')]).read() + if 'sha256:' + hashlib.sha256(config).hexdigest() != BOX_ID: + raise ValueError('Unsupported Box archive identity') + loaded = subprocess.run(['docker', 'load', '-i', str(path)], check=True, capture_output=True, text=True).stdout + match = re.search(r'Loaded image(?: ID)?: (\S+)', loaded) + if not match: + raise ValueError('Docker did not report the loaded Box image') + return match.group(1) + + +def prepare_box(box_archive): + if box_archive: + source = load_verified_archive(box_archive.resolve()) + else: + source = next((ref for ref in (BOX, BOX_TAG, BOX_ID) if image_id(ref) in BOX_IDENTITIES), None) + if not source: + run('docker', 'pull', '--platform', BOX_SPEC['platform'], BOX) + source = BOX + identity = image_id(source) + if identity not in BOX_IDENTITIES: + raise ValueError('Unsupported Box image identity') + run('docker', 'tag', source, BOX_TAG) + return identity + + +def choose_runtime(platform, host_only): + if platform == 'linux/arm64': + return 'grokbot-arm-runtime:local', not host_only + return BOX_TAG, True + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--host-archive', type=Path) parser.add_argument('--box-archive', type=Path, help='Optional original docker-save tar or tar.gz') - parser.add_argument('--box-only', action='store_true', help='Prepare the verified Box image for a standalone execution node') + modes = parser.add_mutually_exclusive_group() + modes.add_argument('--box-only', action='store_true', help='Prepare only the verified desktop') + modes.add_argument('--host-only', action='store_true', help='Build a Host for a separate execution node') parser.add_argument('--image', default='grokbot-host:local') parser.add_argument('--base-image', default='grokbot-patch-base:local') args = parser.parse_args() - manifest = json.loads((ROOT / 'recipes/host/manifest.json').read_text()) + manifest = INPUTS started = time.monotonic() - if args.box_archive: - run('docker', 'load', '-i', str(args.box_archive.resolve())) - probe = subprocess.run(['docker', 'image', 'inspect', BOX, '--format', '{{.Id}}'], capture_output=True, text=True) - if probe.returncode: - local = subprocess.run(['docker', 'image', 'inspect', BOX_ID, '--format', '{{.Id}}'], capture_output=True, text=True) - if local.returncode: - run('docker', 'pull', '--platform', 'linux/amd64', BOX) - else: - run('docker', 'tag', BOX_ID, 'grokbot-box-input:9d2ac1b') - box_image = BOX if subprocess.run(['docker', 'image', 'inspect', BOX], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 else 'grokbot-box-input:9d2ac1b' - identity = subprocess.check_output(['docker', 'image', 'inspect', box_image, '--format', '{{.Id}}'], text=True).strip() - if identity != BOX_ID: - raise ValueError('Unsupported Box image identity') - # docker-save archives do not retain registry RepoDigests. Give Compose a - # verified local tag so offline imports do not trigger another registry pull. - run('docker', 'tag', identity, 'grokbot-box-input:9d2ac1b') - box_image = 'grokbot-box-input:9d2ac1b' + platform = docker_platform() + arm = platform == 'linux/arm64' + if arm and args.host_only and args.box_archive: + raise ValueError('ARM host-only mode does not use a desktop archive.') + if not args.host_only: + check_box_execution(platform) + runtime_image, needs_box = choose_runtime(platform, args.host_only) + identity = prepare_box(args.box_archive) if needs_box else None + box_image = BOX_TAG if identity else None if args.box_only: print(json.dumps({'boxImage': box_image, 'originalImageId': identity, 'inputSeconds': round(time.monotonic()-started, 3)})) return @@ -56,19 +102,26 @@ def main(): archive = work / 'host.tgz' with urllib.request.urlopen(manifest['archive']['url'], timeout=60) as response, archive.open('wb') as target: shutil.copyfileobj(response, target) - if hashlib.sha256(archive.read_bytes()).hexdigest() != manifest['archive']['sha256']: + if file_digest(archive) != manifest['archive']['sha256']: raise ValueError('Unsupported Host archive SHA-256') input_seconds = time.monotonic()-started - run('docker', 'build', '--platform', 'linux/amd64', '-f', str(ROOT / 'release/Dockerfile.base'), '-t', args.base_image, str(ROOT)) + run('docker', 'build', '--platform', platform, '-f', str(ROOT / 'release/Dockerfile.base'), '-t', args.base_image, str(ROOT)) + if arm: + run('docker', 'build', '--platform', platform, '-f', str(ROOT / 'release/Dockerfile.arm-runtime'), + '-t', runtime_image, str(ROOT)) base_seconds = time.monotonic()-started-input_seconds (work / 'inputs').mkdir() shutil.copy2(archive, work / 'inputs/host.tgz') - run('docker', 'build', '--platform', 'linux/amd64', '-f', str(ROOT / 'release/Dockerfile.host'), - '--build-arg', f'PATCH_IMAGE={args.base_image}', '--build-arg', f'BOX_IMAGE={box_image}', '-t', args.image, str(work)) - print(json.dumps({'image': args.image, 'boxImage': box_image, 'inputSeconds': round(input_seconds, 3), + run('docker', 'build', '--platform', platform, '-f', str(ROOT / 'release/Dockerfile.host'), + '--build-arg', f'PATCH_IMAGE={args.base_image}', '--build-arg', f'RUNTIME_IMAGE={runtime_image}', + '--build-arg', f'HOST_REVISION={manifest["archive"]["version"]}', '-t', args.image, str(work)) + print(json.dumps({'image': args.image, 'platform': platform, 'boxImage': box_image, 'inputSeconds': round(input_seconds, 3), 'baseBuildSeconds': round(base_seconds, 3), 'finalBuildSeconds': round(time.monotonic()-started-input_seconds-base_seconds, 3), 'originalImageId': identity, 'distribution': 'local-only'})) if __name__ == '__main__': - main() + try: + main() + except (OSError, ValueError, subprocess.SubprocessError) as error: + raise SystemExit(str(error)) from error diff --git a/host/release/bytepatch.py b/host/release/bytepatch.py index 862458470cb7951fc036d13c50d03efcf3869926..989a3df4f85581b55ace781c5db730e4d2181a6b 100644 --- a/host/release/bytepatch.py +++ b/host/release/bytepatch.py @@ -4,6 +4,7 @@ import argparse import base64 import gzip import hashlib +import io import json from pathlib import Path @@ -15,6 +16,14 @@ def digest(data): return hashlib.sha256(data).hexdigest() +def file_digest(path): + hasher = hashlib.sha256() + with path.open('rb') as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + hasher.update(chunk) + return hasher.hexdigest() + + def index_source(source, width=32, stride=16): result = {} for offset in range(0, len(source) - width + 1, stride): @@ -69,31 +78,47 @@ def create(source, target, index=None): return recipe +class PatchSource: + """One immutable input may feed many recipes; each still checks its own pin.""" + def __init__(self, data): + self._source = memoryview(bytes(data)) + self.sha256 = digest(self._source) + + def write_verified(self, recipe, stream): + # The caller owns an unpublished staging stream until the final digest matches. + source = self._source + if recipe.get('schema') != SCHEMA: + raise ValueError('Unsupported patch schema') + if len(source) != recipe['sourceBytes'] or self.sha256 != recipe['sourceSha256']: + raise ValueError('Unsupported original: SHA-256 mismatch') + size = recipe['targetBytes'] + if type(size) is not int or not 0 <= size <= MAX_BYTES: + raise ValueError('Invalid output size') + written, hasher = 0, hashlib.sha256() + for op in recipe['ops']: + if op[0] == 'copy' and len(op) == 3: + start, length = op[1:] + if type(start) is not int or type(length) is not int or start < 0 or length < 1 or start + length > len(source): + raise ValueError('Invalid COPY range') + data = source[start:start + length] + elif op[0] == 'add' and len(op) == 2: + data = base64.b64decode(op[1], validate=True) + else: + raise ValueError('Invalid patch operation') + written += len(data) + if written > size: + raise ValueError('Patch output overflow') + if stream.write(data) != len(data): + raise OSError('Incomplete patch output write') + hasher.update(data) + if written != size or hasher.hexdigest() != recipe['targetSha256']: + raise ValueError('Patch output verification failed') + + def apply(source, recipe): - if recipe.get('schema') != SCHEMA: - raise ValueError('Unsupported patch schema') - if len(source) != recipe['sourceBytes'] or digest(source) != recipe['sourceSha256']: - raise ValueError('Unsupported original: SHA-256 mismatch') - size = recipe['targetBytes'] - if type(size) is not int or not 0 <= size <= MAX_BYTES: - raise ValueError('Invalid output size') - result = bytearray() - for op in recipe['ops']: - if op[0] == 'copy' and len(op) == 3: - start, length = op[1:] - if type(start) is not int or type(length) is not int or start < 0 or length < 1 or start + length > len(source): - raise ValueError('Invalid COPY range') - data = memoryview(source)[start:start + length] - elif op[0] == 'add' and len(op) == 2: - data = base64.b64decode(op[1], validate=True) - else: - raise ValueError('Invalid patch operation') - if len(result) + len(data) > size: - raise ValueError('Patch output overflow') - result.extend(data) - if len(result) != size or digest(result) != recipe['targetSha256']: - raise ValueError('Patch output verification failed') - return bytes(result) + result = io.BytesIO() + PatchSource(source).write_verified(recipe, result) + return result.getvalue() def load(path): diff --git a/host/release/compose.host.yaml b/host/release/compose.host.yaml index fc18ec2cef5b6a0aefab65040cfef00a41aa1eda..8bc22a02bdb9eff1b2c1212ed3cc889c9b819e2a 100644 --- a/host/release/compose.host.yaml +++ b/host/release/compose.host.yaml @@ -2,7 +2,6 @@ name: grokbot-host services: host: image: ${GROKBOT_HOST_IMAGE:-grokbot-host:local} - platform: linux/amd64 init: true restart: unless-stopped ports: @@ -19,3 +18,5 @@ services: options: { max-size: "10m", max-file: "3" } volumes: host-data: + name: ${COMPOSE_PROJECT_NAME}_host-data + external: ${PROKBOT_EXISTING_VOLUMES:-false} diff --git a/host/release/compose.yaml b/host/release/compose.yaml index 51246f214c135a9fe03a02f4e2185a970cb590f6..76bb6a2a5f36ce083406f70918d0889c89b96c1f 100644 --- a/host/release/compose.yaml +++ b/host/release/compose.yaml @@ -2,7 +2,6 @@ name: grokbot services: host: image: ${GROKBOT_HOST_IMAGE:-grokbot-host:local} - platform: linux/amd64 init: true restart: unless-stopped ports: @@ -12,6 +11,7 @@ services: GROKBOT_BOX_HOST: box GROKBOT_VNC_URL: http://box:6080 GROKBOT_FORK_VNC_URL: http://box:6081 + GROKBOT_HOST_MEMORY_MOUNTS: "1" TZ: ${TZ:-Asia/Singapore} volumes: - host-data:/data @@ -29,10 +29,37 @@ services: volumes: - box-home:/home/box - box-workspace:/workspace + # Keep every mount below RemoteBox.protectedBoxPaths so file-tool checks still apply. + - type: volume + source: host-data + target: /data/runtime/host-data/agents + volume: { subpath: runtime/host-data/agents } + - type: volume + source: host-data + target: /data/runtime/host-data/user-memory + volume: { subpath: runtime/host-data/user-memory } + - type: volume + source: host-data + target: /data/runtime/host-data/workflows + volume: { subpath: runtime/host-data/workflows } + - type: volume + source: host-data + target: /data/runtime/host-data/plugins + volume: { subpath: runtime/host-data/plugins } + - type: volume + source: host-data + target: /data/runtime/host-data/managed-skills + volume: { subpath: runtime/host-data/managed-skills } logging: driver: json-file options: { max-size: "10m", max-file: "3" } volumes: host-data: + name: ${COMPOSE_PROJECT_NAME}_host-data + external: ${PROKBOT_EXISTING_VOLUMES:-false} box-home: + name: ${COMPOSE_PROJECT_NAME}_box-home + external: ${PROKBOT_EXISTING_VOLUMES:-false} box-workspace: + name: ${COMPOSE_PROJECT_NAME}_box-workspace + external: ${PROKBOT_EXISTING_VOLUMES:-false} diff --git a/host/release/data_init.py b/host/release/data_init.py new file mode 100644 index 0000000000000000000000000000000000000000..52528b78d9b9bcc9f42513374ca53d18d42096f5 --- /dev/null +++ b/host/release/data_init.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Create the Host data trees that the execution desktop is allowed to see.""" +import argparse +import json +import os +from pathlib import Path +import sys + +from backup import DATA_TREES + +UID = 1000 +GID = 1000 +MODE = 0o750 + + +def metadata(path, *, uid=UID, gid=GID, mode=MODE): + if os.name == 'posix': + os.chown(path, uid, gid, follow_symlinks=False) + path.chmod(mode, follow_symlinks=False) + + +def ensure_directory(path, *, trusted_root=Path('/data'), uid=UID, gid=GID, mode=MODE): + path = Path(path) + if not path.is_absolute() or '..' in path.parts: + raise ValueError('Host data path must be an absolute path without parent traversal.') + trusted_root = Path(trusted_root) + if not path.is_relative_to(trusted_root): + raise ValueError(f'Host data path must stay below {trusted_root}.') + current = trusted_root + created = False + for part in path.relative_to(trusted_root).parts: + current /= part + try: + info = current.lstat() + except FileNotFoundError: + current.mkdir(mode=mode) + metadata(current, uid=uid, gid=gid, mode=mode) + created = True + continue + if current.is_symlink(): + raise ValueError(f'Host data path contains a symlink: {current}') + if not current.is_dir(): + raise ValueError(f'Host data path is not a directory: {current}') + return created + + +def initialise(host_data, *, trusted_root=Path('/data'), uid=UID, gid=GID, mode=MODE): + host_data = Path(host_data) + root_created = ensure_directory(host_data, trusted_root=trusted_root, uid=uid, gid=gid, mode=mode) + created = [] + for tree in DATA_TREES: + path = host_data / tree + if path.exists() and not path.is_dir(): + raise ValueError(f'Host data tree is not a directory: {path}') + if path.is_symlink(): + raise ValueError(f'Host data tree is a symlink: {path}') + if not path.exists(): + path.mkdir(mode=mode) + metadata(path, uid=uid, gid=gid, mode=mode) + created.append(tree) + return {'rootCreated': root_created, 'created': created, 'trees': list(DATA_TREES)} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('host_data', type=Path, help='Path to runtime/host-data inside the Host data volume') + args = parser.parse_args(argv) + print(json.dumps(initialise(args.host_data), sort_keys=True)) + + +if __name__ == '__main__': + try: + main() + except (OSError, ValueError) as error: + raise SystemExit(str(error)) from error diff --git a/host/release/patch-host.py b/host/release/patch-host.py index ff64ea0453ffc5b84f82dfcf5e6268392e03e4fe..11b8a340983f623481e712bff715000dde86f5a3 100644 --- a/host/release/patch-host.py +++ b/host/release/patch-host.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Prepare the pinned Host locally from an original archive and COPY/ADD patches.""" import argparse +import hashlib import json from pathlib import Path import shutil @@ -8,7 +9,7 @@ import tarfile import tempfile import time import urllib.request -from bytepatch import apply, digest, load +from bytepatch import PatchSource, file_digest, load ROOT = Path(__file__).resolve().parents[1] @@ -33,6 +34,30 @@ def extract(source, destination): target.chmod(entry.mode & 0o777) +def verify_reliability_manifest(seed): + """Reject generated reliability seeds whose manifest no longer matches them.""" + directory = seed / 'release-reliability' + manifest_path = directory / 'manifest.json' + if not manifest_path.exists(): + return + manifest = json.loads(manifest_path.read_text()) + digest = manifest.get('digest') + if not isinstance(digest, str) or len(digest) != 64: + raise ValueError('Invalid prepared reliability manifest digest') + files = manifest.get('files') + if not isinstance(files, list): + raise ValueError('Invalid prepared reliability manifest files') + for entry in files: + if not isinstance(entry, dict) or set(entry) != {'name', 'sha256'}: + raise ValueError('Invalid prepared reliability manifest entry') + name, expected = entry['name'], entry['sha256'] + if not isinstance(name, str) or Path(name).name != name or not isinstance(expected, str) or len(expected) != 64: + raise ValueError('Invalid prepared reliability manifest entry') + actual = hashlib.sha256((directory / name).read_bytes()).hexdigest() + if actual != expected: + raise ValueError('Prepared reliability manifest mismatch: ' + name) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--archive', type=Path, help='User-provided stable Host archive; otherwise download the pinned URL') @@ -50,11 +75,13 @@ def main(): archive = work / 'host.tgz' with urllib.request.urlopen(spec['archive']['url'], timeout=60) as response, archive.open('wb') as target: shutil.copyfileobj(response, target) - if digest(archive.read_bytes()) != spec['archive']['sha256']: + if file_digest(archive) != spec['archive']['sha256']: raise ValueError('Unsupported original Host archive: SHA-256 mismatch') download_seconds = time.monotonic() - started extract(archive, work / 'original') original = work / 'original' / 'sand-host' + if (original / 'version').read_text().strip() != spec['archive']['version']: + raise ValueError('Pinned Host revision does not match the archive') source_cache = {} seed = work / 'seed' for record in spec['files']: @@ -63,11 +90,15 @@ def main(): if any(p.is_absolute() or '..' in p.parts for p in (source_path, target_path)): raise ValueError('Unsafe patch path') if record['source'] not in source_cache: - source_cache[record['source']] = (original / source_path).read_bytes() + source_cache[record['source']] = PatchSource((original / source_path).read_bytes()) + if source_cache[record['source']].sha256 != spec['sourceSha256'][record['source']]: + raise ValueError('Pinned Host source digest mismatch: ' + record['source']) source = source_cache[record['source']] target = seed / target_path target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(apply(source, load(ROOT / 'recipes/host' / record['patch']))) + with target.open('xb') as output: + source.write_verified(load(ROOT / 'recipes/host' / record['patch']), output) + verify_reliability_manifest(seed) args.output.mkdir(mode=0o700) shutil.move(str(original), str(args.output / 'original')) shutil.move(str(seed), str(args.output / 'seed')) diff --git a/host/release/platforms.py b/host/release/platforms.py new file mode 100644 index 0000000000000000000000000000000000000000..3634e76b51b66e698e346f8686c71eec8783c73c --- /dev/null +++ b/host/release/platforms.py @@ -0,0 +1,37 @@ +"""Deployment platform policy. Detect the Docker daemon, not the CLI machine.""" +import json +from pathlib import Path +import subprocess + +ROOT = Path(__file__).resolve().parents[1] +INPUTS = json.loads((ROOT / 'recipes/host/manifest.json').read_text(encoding='utf-8')) +BOX = INPUTS['box'] + + +def host_platform(os_name, architecture): + arch = {'amd64': 'amd64', 'x86_64': 'amd64', 'arm64': 'arm64', 'aarch64': 'arm64'}.get(architecture.lower()) + if os_name.lower() != 'linux' or not arch: + raise ValueError(f'Unsupported Docker server: {os_name}/{architecture}. Use 64-bit Linux (amd64 or arm64).') + return 'linux/' + arch + + +def docker_platform(): + result = subprocess.run(['docker', 'info', '--format', '{{.OSType}}/{{.Architecture}}'], + check=True, text=True, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL) + return host_platform(*result.stdout.strip().split('/', 1)) + + +def check_box_execution(platform): + if platform == BOX['platform']: + return + # Probe a real amd64 process before downloading the much larger desktop. No host mounts or privileges. + cmd = ['docker', 'run', '--rm', '--platform', BOX['platform'], '--network', 'none', '--read-only', + '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', 'busybox:1.37', 'uname', '-m'] + try: + result = subprocess.run(cmd, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=120) + except subprocess.TimeoutExpired: + raise ValueError('amd64 probe timed out. Check access to busybox:1.37 and binfmt, or choose a separate execution node.') from None + if result.returncode or result.stdout.strip() != 'x86_64': + detail = result.stderr.strip().splitlines()[-1:] or [result.stdout.strip() or 'no output'] + raise ValueError('amd64 desktop probe failed: ' + detail[0] + '. Check registry access and Linux ' + 'binfmt/QEMU x86-64 support, or use a separate amd64 execution node (host-only mode).') diff --git a/host/runtime/anthropic-messages.mjs b/host/runtime/anthropic-messages.mjs new file mode 100644 index 0000000000000000000000000000000000000000..60be02234ceccf8e49bd49bad7eb7aad3725b82c --- /dev/null +++ b/host/runtime/anthropic-messages.mjs @@ -0,0 +1,326 @@ +// Anthropic Messages API format for the configured model. +// The original Harness speaks AI SDK CoreMessages; this module translates them to +// POST /v1/messages and back, keeping images, documents, tool results and signed thinking. +import { explicitEffort, fileKind, fileText, mediaUrl, messageParts, ModelRequestError, parseDataUrl, parseEvent, + parseToolArguments, postWithFallback, providerError, readSse, reasoningOrigin, reasoningProviderOptions, replayRejected, + streamToolCalls, textValue, toolSchema, unsupportedFileNote } from './model-common.mjs'; + +export const FORMAT = 'anthropic'; +export const ANTHROPIC_VERSION = '2026-10-21'; +const FALLBACK_BETA = 'server-side-fallback-2026-07-01'; +const INTERLEAVED_BETA = 'interleaved-thinking-2025-05-14'; +const BUDGETS = { minimal: 1024, low: 2048, medium: 8192, high: 16384, xhigh: 24576, max: 32000 }; + +/** Accept a host, a /v1 root or the full /v1/messages URL. */ +export function anthropicEndpoint(baseUrl, resource = 'messages') { + const url = new URL(baseUrl); + if (!['http:', 'https:'].includes(url.protocol)) throw new TypeError('baseUrl must use HTTP or HTTPS'); + let path = url.pathname.replace(/\/+$/, ''); + if (path.endsWith('/messages')) path = path.slice(0, -'/messages'.length); + if (!path.endsWith('/v1')) path += '/v1'; + url.pathname = `${path}/${resource}`; + url.search = ''; url.hash = ''; + return url.href; +} + +/** + * Thinking controls differ by generation: Claude 4.6 and later think adaptively and take + * an effort level; Claude 3.7 to 4.5 take a thinking budget (Opus 4.5 also takes effort). + */ +export function claudeTraits(model) { + const id = String(model).toLowerCase(); + const modern = /claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?![\d.])/.exec(id); + const old = /claude-(\d)-(\d)-(opus|sonnet|haiku)/.exec(id); + const family = modern?.[1] ?? old?.[3]; + const version = modern ? Number(modern[2]) + Number(modern[3] ?? 0) / 10 : old ? Number(old[1]) + Number(old[2]) / 10 : NaN; + if (!family || !Number.isFinite(version)) return { known: false, adaptive: true, efforts: ['low', 'medium', 'high', 'xhigh', 'max'], disable: 'disabled', budget: false, maxOutput: 64_000 }; + const adaptive = version >= 4.6; + const efforts = adaptive ? ['low', 'medium', 'high', ...(version >= 4.7 ? ['xhigh'] : []), 'max'] + : family === 'opus' && version === 4.5 ? ['low', 'medium', 'high'] : []; + // How "no thinking" is expressed: never for always-thinking models. + const disable = ['fable', 'mythos'].includes(family) || (family === 'opus' && version >= 5.5) ? 'never' + : family === 'sonnet' && version >= 5.5 ? 'between_tools' : adaptive ? 'disabled' : 'omit'; + return { known: true, family, version, adaptive, efforts, disable, budget: !adaptive && version >= 3.7, + maxOutput: adaptive ? 128_000 : family === 'opus' && version < 4.5 ? 32_000 : 64_000, + fallbacks: /^claude-(?:opus-5-5|opus-5|fable-5-1|sonnet-5-5)$/.test(id) }; +} + +/** The closest supported level: minimal maps to low, unsupported upper levels step down. */ +function supportedEffort(level, efforts) { + if (!level || !efforts.length) return undefined; + const order = ['low', 'medium', 'high', 'xhigh', 'max']; + let index = order.indexOf(level === 'minimal' ? 'low' : level); + while (index >= 0 && !efforts.includes(order[index])) index--; + return index >= 0 ? order[index] : efforts[0]; +} + +/** Request parameters shared by chat, test and review requests. */ +export function anthropicOptions(model, { effort, maxTokens } = {}) { + const traits = claudeTraits(model), level = explicitEffort(effort); + let limit = Number.isSafeInteger(maxTokens) && maxTokens > 0 ? Math.min(maxTokens, traits.maxOutput) : Math.min(64_000, traits.maxOutput); + const options = {}; + if (level === 'none' && traits.disable !== 'never') { + if (traits.disable === 'disabled' || traits.disable === 'between_tools') options.thinking = { type: traits.disable }; + } else if (traits.adaptive) { + options.thinking = { type: 'adaptive', display: 'summarized' }; + const supported = supportedEffort(level === 'none' ? 'low' : level, traits.efforts); + if (supported) options.output_config = { effort: supported }; + } else if (traits.budget && level && level !== 'none') { + limit = Math.max(limit, Math.min(traits.maxOutput, BUDGETS[level] + 4096)); + options.thinking = { type: 'enabled', budget_tokens: Math.max(1024, Math.min(BUDGETS[level], limit - 2048)) }; + const supported = supportedEffort(level, traits.efforts); + if (supported) options.output_config = { effort: supported }; + } + if (traits.fallbacks) options.fallbacks = 'default'; + return { max_tokens: limit, ...options }; +} + +export function anthropicHeaders(apiKey, { stream = false, body = {} } = {}) { + const headers = new Headers({ 'content-type': 'application/json', 'anthropic-version': ANTHROPIC_VERSION }); + if (stream) headers.set('accept', 'text/event-stream'); + if (apiKey) headers.set('x-api-key', apiKey); + const betas = [...(body.fallbacks ? [FALLBACK_BETA] : []), ...(body.thinking?.type === 'enabled' ? [INTERLEAVED_BETA] : [])]; + if (betas.length) headers.set('anthropic-beta', betas.join(',')); + return headers; +} + +function source(url) { + const parsed = parseDataUrl(url); + if (parsed) return { type: 'base64', media_type: parsed.mediaType, data: parsed.data }; + if (/^https?:\/\//i.test(url)) return { type: 'url', url }; + throw new TypeError('Unsupported media URL'); +} + +function userBlock(part) { + if (part.type === 'text') return part.text ? { type: 'text', text: part.text } : null; + if (part.type === 'image') return { type: 'image', source: source(mediaUrl(part)) }; + if (part.type === 'file') { + const kind = fileKind(part); + if (kind === 'image') return { type: 'image', source: source(mediaUrl(part, part.mimeType)) }; + if (kind === 'pdf') return { type: 'document', source: source(mediaUrl(part, part.mimeType)), ...(part.filename ? { title: part.filename } : {}) }; + if (kind === 'text') return { type: 'document', source: { type: 'text', media_type: 'text/plain', data: fileText(part) }, ...(part.filename ? { title: part.filename } : {}) }; + return { type: 'text', text: unsupportedFileNote(part) }; + } + throw new TypeError(`Unsupported user content type: ${part.type}`); +} + +/** Thinking that Anthropic wrote; other formats' reasoning is not replayed here. */ +function anthropicReasoning(part, providerId) { + const origin = reasoningOrigin(part); + // Response model IDs can differ from configured aliases (date snapshots or + // gateways rewriting the name), but signed Anthropic thinking is still valid + // for the same provider. API format and provider identity remain isolation + // boundaries. + if (origin.providerId && providerId && origin.providerId !== providerId) return false; + if (origin.format) return origin.format === FORMAT; + if (part.type === 'reasoning') return Boolean(part.signature) && !origin.summarized; + return !origin.model || /claude/i.test(origin.model); +} + +/** + * Convert CoreMessages. Signed thinking is replayed only when every Anthropic reasoning + * part still carries its signature; otherwise all thinking is stripped, which the API + * accepts, instead of sending a history with blocks missing from the middle. + */ +export function convertAnthropicMessages(messages, { model, providerId, stripThinking = false } = {}) { + const reasoningParts = messages.filter(message => message.role === 'assistant' && Array.isArray(message.content)) + .flatMap(message => message.content.filter(part => (part.type === 'reasoning' || part.type === 'redacted-reasoning') && anthropicReasoning(part, providerId))); + const replayThinking = !stripThinking && reasoningParts.every(part => + part.type === 'redacted-reasoning' ? typeof part.data === 'string' && part.data : typeof part.signature === 'string' && part.signature); + const system = [], output = []; + let leading = true; + const push = (role, content) => { + const blocks = content.filter(Boolean); + if (!blocks.length) return; + const previous = output.at(-1); + if (previous?.role === role) previous.content.push(...blocks); + else output.push({ role, content: blocks }); + }; + for (const message of messages) { + const parts = messageParts(message); + if (message.role === 'system' || message.role === 'developer') { + const text = parts.filter(part => part.type === 'text').map(part => part.text).join(''); + if (!text) continue; + if (leading) system.push({ type: 'text', text }); + // Later operator text stays in order as user-visible context. + else push('user', [{ type: 'text', text: `\n${text}\n` }]); + continue; + } + leading = false; + if (message.role === 'user') { + push('user', parts.map(userBlock)); + } else if (message.role === 'assistant') { + push('assistant', parts.map(part => { + if (part.type === 'text') return part.text ? { type: 'text', text: part.text } : null; + if (part.type === 'reasoning') return replayThinking && anthropicReasoning(part, providerId) ? { type: 'thinking', thinking: part.text ?? '', signature: part.signature } : null; + if (part.type === 'redacted-reasoning') { + if (!replayThinking || !anthropicReasoning(part, providerId)) return null; + return reasoningOrigin(part).emptyThinking ? { type: 'thinking', thinking: '', signature: part.data } : { type: 'redacted_thinking', data: part.data }; + } + if (part.type === 'tool-call') return { type: 'tool_use', id: part.toolCallId, name: part.toolName, + input: typeof part.args === 'string' ? JSON.parse(part.args || '{}') : part.args ?? {} }; + return null; + })); + } else if (message.role === 'tool') { + push('user', parts.map(part => { + if (part.type !== 'tool-result' || !part.toolCallId) throw new TypeError('Tool messages require tool-result parts and toolCallId'); + const extra = part.experimental_content ?? []; + const text = part.result === undefined + ? extra.filter(item => item.type === 'text').map(item => item.text).join('\n') : textValue(part.result); + const content = [...(text ? [{ type: 'text', text }] : []), + ...extra.filter(item => item.type === 'image').map(item => ({ type: 'image', source: source(mediaUrl(item)) }))]; + return { type: 'tool_result', tool_use_id: part.toolCallId, content: content.length ? content : [{ type: 'text', text: '(empty)' }], + ...(part.isError ? { is_error: true } : {}) }; + })); + } else { + throw new TypeError(`Unsupported message role: ${message.role}`); + } + } + // Tool results must lead the user turn that answers a tool call. + for (const message of output) { + if (message.role === 'user') message.content.sort((a, b) => (a.type === 'tool_result' ? 0 : 1) - (b.type === 'tool_result' ? 0 : 1)); + } + if (output[0]?.role === 'assistant') output.unshift({ role: 'user', content: [{ type: 'text', text: '(conversation start)' }] }); + // Two cache breakpoints: tools + system, and the whole history for the next turn. + if (system.length) system.at(-1).cache_control = { type: 'ephemeral' }; + const lastBlock = output.at(-1)?.content.at(-1); + if (lastBlock && ['text', 'image', 'document', 'tool_result'].includes(lastBlock.type)) lastBlock.cache_control = { type: 'ephemeral' }; + return { system, messages: output, replayedThinking: replayThinking && reasoningParts.length > 0 }; +} + +export function convertAnthropicTools(tools = []) { + return tools.map(tool => { + const { name, description, parameters } = toolSchema(tool); + return { name, description, input_schema: parameters }; + }); +} + +/** Normalize Anthropic usage to the OpenAI-style fields the usage ledger records. */ +export function anthropicUsage(raw = {}) { + const count = value => Number.isFinite(value) && value >= 0 ? value : 0; + const uncached = count(raw.input_tokens), cacheRead = count(raw.cache_read_input_tokens), + cacheWrite = count(raw.cache_creation_input_tokens), output = count(raw.output_tokens); + const input = uncached + cacheRead + cacheWrite; + return { prompt_tokens: input, completion_tokens: output, total_tokens: input + output, + prompt_tokens_details: { cached_tokens: cacheRead }, cache_creation_input_tokens: cacheWrite, + completion_tokens_details: { reasoning_tokens: count(raw.output_tokens_details?.thinking_tokens) } }; +} + +/** True for a 400 caused by thinking blocks that no longer match their conversation. */ +export function isThinkingReplayError(status, message) { + return replayRejected({ status, message }); +} + +const OPTIONAL = ['fallbacks', 'thinking.display', 'output_config']; + +/** One streamed Messages API turn; yields Harness stream parts and returns the assembled message. */ +export async function* anthropicTurn(context) { + const { fetchImpl, endpoint, apiKey, headers, model, messages, tools, effort, maxTokens, signal, waitForIO, state, + providerId, notifyRequest, onModel, onId, onUsage } = context; + const anthropicTools = convertAnthropicTools(tools); + let replayed = false; + const { http } = await postWithFallback({ fetchImpl, url: endpoint, apiKey, signal, waitForIO, state, optional: OPTIONAL, + headers: body => { + const value = anthropicHeaders(apiKey, { stream: true, body }); + for (const [key, entry] of new Headers(headers)) value.set(key, entry); + return value; + }, + // Signed thinking from an edited or summarized history: retry without it. + fallbacks: [{ name: 'retry without replayed thinking', applies: error => replayed && replayRejected(error), apply: () => { state.stripReasoning = true; } }], + build: () => { + const converted = convertAnthropicMessages(messages, { model, providerId, stripThinking: state.stripReasoning }); + replayed = converted.replayedThinking; + return { model, ...anthropicOptions(model, { effort, maxTokens }), stream: true, + ...(converted.system.length ? { system: converted.system } : {}), messages: converted.messages, + ...(anthropicTools.length ? { tools: anthropicTools } : {}) }; + } }); + notifyRequest(http.headers.get('request-id') ?? http.headers.get('x-request-id')); + let id, responseModel = model, stopReason, stopDetails, stopped = false; + const rawUsage = {}, blocks = new Map(); + const reasoningOptions = () => ({ providerOptions: reasoningProviderOptions({ format: FORMAT, model: responseModel, providerId }) }); + const emptyOptions = () => ({ providerOptions: reasoningProviderOptions({ format: FORMAT, model: responseModel, providerId, emptyThinking: true }) }); + const mergeUsage = usage => { + if (!usage) return; + for (const [key, value] of Object.entries(usage)) if (value !== null && value !== undefined) rawUsage[key] = value; + onUsage(anthropicUsage(rawUsage)); + }; + for await (const data of readSse(http.body, { waitForIO })) { + signal.throwIfAborted(); + const event = parseEvent(data); + if (event.type === 'error') throw providerError(event, undefined, http.headers, apiKey); + if (event.type === 'message_start') { + const message = event.message ?? {}; + if (message.id) { id = message.id; onId(id); notifyRequest(id); } + if (message.model) { responseModel = message.model; onModel(responseModel); } + mergeUsage(message.usage); + } else if (event.type === 'content_block_start') { + const block = event.content_block ?? {}; + if (block.type === 'text') { + blocks.set(event.index, { type: 'text', text: block.text ?? '' }); + if (block.text) yield { type: 'text-delta', textDelta: block.text }; + } else if (block.type === 'thinking') { + blocks.set(event.index, { type: 'reasoning', text: block.thinking ?? '', signature: block.signature ?? '' }); + if (block.thinking) yield { type: 'reasoning', textDelta: block.thinking, ...reasoningOptions() }; + } else if (block.type === 'redacted_thinking') { + blocks.set(event.index, { type: 'redacted-reasoning', data: block.data ?? '' }); + if (block.data) yield { type: 'redacted-reasoning', data: block.data, ...reasoningOptions() }; + } else if (block.type === 'tool_use') { + blocks.set(event.index, { type: 'tool-use', id: block.id ?? '', name: block.name ?? '', input: block.input, json: '' }); + } + } else if (event.type === 'content_block_delta') { + const block = blocks.get(event.index), delta = event.delta ?? {}; + if (!block) continue; + if (delta.type === 'text_delta' && block.type === 'text' && delta.text) { + block.text += delta.text; + yield { type: 'text-delta', textDelta: delta.text }; + } else if (delta.type === 'thinking_delta' && block.type === 'reasoning' && delta.thinking) { + block.text += delta.thinking; + yield { type: 'reasoning', textDelta: delta.thinking, ...reasoningOptions() }; + } else if (delta.type === 'signature_delta' && block.type === 'reasoning') { + block.signature += delta.signature ?? ''; + } else if (delta.type === 'input_json_delta' && block.type === 'tool-use') { + block.json += delta.partial_json ?? ''; + } + } else if (event.type === 'content_block_stop') { + const block = blocks.get(event.index); + // The Harness keeps reasoning only with readable text; a signed block without text + // travels as a redacted part holding its signature and is restored on replay. + if (block?.type === 'reasoning' && block.signature) { + if (block.text) yield { type: 'reasoning-signature', signature: block.signature }; + else yield { type: 'redacted-reasoning', data: block.signature, ...emptyOptions() }; + } + } else if (event.type === 'message_delta') { + if (event.delta?.stop_reason) stopReason = event.delta.stop_reason; + if (event.delta?.stop_details) stopDetails = event.delta.stop_details; + mergeUsage(event.usage); + } else if (event.type === 'message_stop') { + stopped = true; + break; + } + } + signal.throwIfAborted(); + if (stopReason === 'max_tokens') throw new ModelRequestError('Model response stopped with max_tokens', { code: 'length' }); + if (stopReason === 'model_context_window_exceeded') throw new ModelRequestError('Model context window exceeded', { code: 'context_length_exceeded' }); + if (stopReason === 'refusal') { + const category = stopDetails?.category ? ` (${stopDetails.category})` : ''; + throw new ModelRequestError(`Model declined this request${category}`, { code: 'content_filter' }); + } + if (!stopped || !stopReason) throw new ModelRequestError('Model SSE stream ended before a completion marker'); + if (!['end_turn', 'stop_sequence', 'tool_use'].includes(stopReason)) throw new ModelRequestError(`Unsupported model stop reason: ${stopReason}`); + const content = [], calls = []; + for (const [, block] of [...blocks.entries()].sort(([a], [b]) => a - b)) { + if (block.type === 'text') { if (block.text) content.push(block); continue; } + if (block.type === 'reasoning' && !block.text) { + if (block.signature) content.push({ type: 'redacted-reasoning', data: block.signature, ...emptyOptions() }); + continue; + } + if (block.type === 'reasoning' || block.type === 'redacted-reasoning') { content.push({ ...block, ...reasoningOptions() }); continue; } + if (!block.id || !block.name) throw new ModelRequestError('Incomplete model tool call identity'); + const call = { type: 'tool-call', toolCallId: block.id, toolName: block.name, + args: parseToolArguments(block.name, block.json || JSON.stringify(block.input)) }; + calls.push(call); content.push(call); + } + if ((stopReason === 'tool_use') !== Boolean(calls.length)) throw new ModelRequestError('Model tool calls do not match the stop reason'); + yield* streamToolCalls(calls, messages, signal); + return { id, model: responseModel, content, toolCalls: calls.length, usage: anthropicUsage(rawUsage) }; +} diff --git a/host/runtime/codex-prompt.mjs b/host/runtime/codex-prompt.mjs index 8bdc6ad1371a7ae20b346468ab9f0dc813c66740..298d9113c57d0d0367d591bedcee7894c2aae706 100644 --- a/host/runtime/codex-prompt.mjs +++ b/host/runtime/codex-prompt.mjs @@ -1,9 +1,9 @@ /** Applied to both standard and slim prompt sections; official CloudAgent stays disabled. */ export const codexCodingGuidance = [ - 'For non-trivial coding work (implementing features, fixing bugs, refactoring, or broad repository investigation), delegate to Codex on a connected Mac. Discover the paired Mac codex_start, codex_status, codex_continue, codex_cancel and codex_list tools through your dynamic MCP tool catalog. The official CloudAgent service is not used.', - 'Pass a clear task, relevant context, constraints and success criteria. Use an existing absolute project directory on the selected Mac, or omit cwd for a new isolated project. Codex uses the account and default model configured on that Mac. It may obtain a repository checkout inside the task directory when required by the user’s coding request.', - 'codex_start returns a job ID before the task finishes. Use codex_status with waitMs:25000 to wait for progress and completion; keep the user informed and do not report success until status is completed and the result is checked. Continue the same job with codex_continue for follow-up work. Use codex_cancel when the user stops it. A disconnected Mac or interrupted task is not a completed task.', - 'Keep the returned Mac, job and project identifiers together. Jobs and results belong to this Bot on that Mac. When Codex requests user input, ask the user and supply their actual answers. Mac local execution permissions still apply. If no Codex-capable Mac is connected, explain that it must be connected or Codex installed/signed in; do not substitute an unavailable official CloudAgent or launch Codex through a shell command.', + 'For non-trivial coding work (implementing features, fixing bugs, refactoring, or broad repository investigation), delegate to Codex on a connected computer. Discover the paired computer’s codex_start, codex_status, codex_continue, codex_cancel and codex_list tools through your dynamic MCP tool catalog. The official CloudAgent service is not used.', + 'Pass a clear task, relevant context, constraints and success criteria. Use an existing absolute project directory on the selected computer, in that computer’s path syntax, or omit cwd for a new isolated project. Codex uses the account and default model configured on that computer. It may obtain a repository checkout inside the task directory when required by the user’s coding request.', + 'codex_start returns a job ID before the task finishes. Use codex_status with waitMs:25000 to wait for progress and completion; keep the user informed and do not report success until status is completed and the result is checked. Continue the same job with codex_continue for follow-up work. Use codex_cancel when the user stops it. A disconnected computer or interrupted task is not a completed task.', + 'Keep the returned computer, job and project identifiers together. Jobs and results belong to this Bot on that computer. When Codex requests user input, ask the user and supply their actual answers. Local execution permissions on that computer still apply. If no Codex-capable computer is connected, explain that it must be connected or Codex installed/signed in; do not substitute an unavailable official CloudAgent or launch Codex through a shell command.', ]; export function localCodexSection(section, options) { @@ -12,7 +12,7 @@ export function localCodexSection(section, options) { if (section.heading !== '## Where you work') return section; return { ...section, body: section.body.map(line => { if (!line.includes('Repository work')) return line; - return line.slice(0, line.indexOf('Repository work')) + 'Repository coding work uses the connected Mac Codex tools described in Code changes.'; + return line.slice(0, line.indexOf('Repository work')) + 'Repository coding work uses the connected computer Codex tools described in Code changes.'; }) }; } diff --git a/host/runtime/config.mjs b/host/runtime/config.mjs index 48132d80f99ec946b2bb77a8f339f4aa9ce96787..ebab10f858c05034395ce92d773ac6383a3cc27c 100644 --- a/host/runtime/config.mjs +++ b/host/runtime/config.mjs @@ -1,27 +1,58 @@ import { readFile } from 'node:fs/promises'; import { resolve } from 'node:path'; -import { parseModelPolicy } from './model-policy.mjs'; +import { defaultPolicy, parseModelPolicy } from './model-policy.mjs'; +import { API_FORMATS, MODEL_ROUTING_ENV, modelRouteForAgent, parseModelRouting } from './model-routing.mjs'; export const root = resolve(import.meta.dirname, '..'); -export async function loadModelConfig({ env = process.env } = {}) { - const path = env.GROKBOT_MODEL_ENV ?? resolve(root, '.runtime/model.env'); - const file = await readFile(path, 'utf8'); - const values = Object.fromEntries(file.split(/\r?\n/).filter(line => line && !line.startsWith('#')) + +function envValues(source) { + return Object.fromEntries(source.split(/\r?\n/).filter(line => line && !line.startsWith('#') && line.includes('=')) .map(line => { const i = line.indexOf('='); return [line.slice(0, i), line.slice(i + 1)]; })); - if (!values.OPENAI_BASE_URL || !values.OPENAI_API_KEY) throw new Error('Missing model configuration'); - const capacity = String(env.OPENAI_CONTEXT_WINDOW_TOKENS ?? values.OPENAI_CONTEXT_WINDOW_TOKENS ?? '').trim(); - const contextWindowTokens = capacity === '' ? 0 : Number(capacity); - if ((capacity !== '' && !/^\d+$/.test(capacity)) || !Number.isSafeInteger(contextWindowTokens)) { +} + +function contextCapacity(value) { + const capacity = String(value ?? '').trim(); + const parsed = capacity === '' ? 0 : Number(capacity); + if ((capacity !== '' && !/^\d+$/.test(capacity)) || !Number.isSafeInteger(parsed)) throw new Error('OPENAI_CONTEXT_WINDOW_TOKENS must be a nonnegative safe integer'); - } + return parsed; +} + +function legacyConfig(values, env) { + const model = env.GROKBOT_MODEL ?? values.OPENAI_MODEL ?? 'deepseek-v4.1-flash'; return { baseUrl: values.OPENAI_BASE_URL, apiKey: values.OPENAI_API_KEY, - model: env.GROKBOT_MODEL ?? values.OPENAI_MODEL ?? 'deepseek-v4.1-flash', - contextWindowTokens, - policy: parseModelPolicy(values.GROKBOT_MODEL_POLICY, env.GROKBOT_MODEL ?? values.OPENAI_MODEL), + apiFormat: API_FORMATS.includes(values.MODEL_API_FORMAT) ? values.MODEL_API_FORMAT : 'openai', + model, + contextWindowTokens: contextCapacity(env.OPENAI_CONTEXT_WINDOW_TOKENS ?? values.OPENAI_CONTEXT_WINDOW_TOKENS), + policy: parseModelPolicy(values.GROKBOT_MODEL_POLICY, model), jevApiKey: values.JEV_API_KEY || '', + }; +} + +export async function loadModelConfig({ env = process.env } = {}) { + const path = env.GROKBOT_MODEL_ENV ?? resolve(root, '.runtime/model.env'); + const values = envValues(await readFile(path, 'utf8')); + const legacy = legacyConfig(values, env); + const common = { + jevApiKey: legacy.jevApiKey, usageDirectory: resolve(env.GROKBOT_DATA_DIR ?? resolve(path, '..'), 'usage'), routingDirectory: resolve(env.GROKBOT_DATA_DIR ?? resolve(path, '..'), 'routing'), }; + if (!values[MODEL_ROUTING_ENV]) { + if (!legacy.baseUrl || !legacy.apiKey) throw new Error('Missing model configuration'); + return { ...legacy, ...common, modelBaseUrls: [legacy.baseUrl] }; + } + const { config: modelRouting } = parseModelRouting(values[MODEL_ROUTING_ENV], legacy); + const route = modelRouteForAgent(modelRouting); + if (!route.baseUrl || !route.apiKey || !route.model) throw new Error('Missing model configuration'); + // Auto-review intentionally remains on the global primary route. It does not inherit a Bot's + // fallback chain because approval decisions should not change provider halfway through a review. + const policy = defaultPolicy(route.model); + policy.models = [{ id: route.model, efforts: route.efforts, + contextWindowTokens: route.contextWindowTokens, summaryThresholdTokens: route.summaryThresholdTokens }]; + return { ...common, modelRouting, baseUrl: route.baseUrl, apiKey: route.apiKey, apiFormat: route.apiFormat, + model: route.model, contextWindowTokens: route.contextWindowTokens, policy, + modelBaseUrls: [...new Set(modelRouting.providers.map(provider => provider.baseUrl))] }; } diff --git a/host/runtime/host-auto-review.mjs b/host/runtime/host-auto-review.mjs index 66197be2d46308e625e74f514239b93871630361..35fcc714aed3308e01d88a0c5ba4f6e89eae3b30 100644 --- a/host/runtime/host-auto-review.mjs +++ b/host/runtime/host-auto-review.mjs @@ -1,10 +1,105 @@ import { randomUUID } from 'node:crypto'; import { recordUsage } from './usage-ledger.mjs'; +import { anthropicEndpoint, anthropicHeaders, anthropicOptions, anthropicUsage } from './anthropic-messages.mjs'; +import { chatEndpoint, chatReasoning, maxTokensParameter } from './openai-chat.mjs'; +import { reasons, responsesEndpoint, responsesUsage } from './openai-responses.mjs'; +import { postWithFallback } from './model-common.mjs'; + +const OUTPUT_LIMIT = 16_000; +// Classification needs little reasoning; use the lowest level the model offers. +function reviewEffort(config) { + const efforts = config.policy?.models?.find(entry => entry.id === config.model)?.efforts ?? []; + return ['low', 'minimal', 'medium'].find(level => efforts.includes(level)); +} +/** The model answered, but not with one valid classification; worth one more attempt. */ +class ReviewOutputError extends Error {} +const forcedChoiceRejected = error => error.status === 400 && /tool_choice|tool choice/i.test(error.message); +const onlyTool = name => `\n\nRespond only by calling the ${name} tool exactly once.`; + +function single(calls, name, truncated) { + if (truncated || calls.length !== 1 || calls[0].name !== name) throw new ReviewOutputError('Auto-review model did not return one complete classification'); + if (typeof calls[0].arguments !== 'string') return calls[0].arguments; + try { return JSON.parse(calls[0].arguments); } + catch { throw new ReviewOutputError('Auto-review model returned invalid JSON'); } +} + +async function classifyWithChat(config, library, tool, content, signal, fetchImpl, state) { + let forced = !state.autoToolChoice; + const { http } = await postWithFallback({ fetchImpl, url: chatEndpoint(config.baseUrl), apiKey: config.apiKey, signal, state, + headers: { 'content-type': 'application/json', authorization: `Bearer ${config.apiKey}` }, + optional: ['reasoning_effort', 'thinking', 'parallel_tool_calls', 'max_tokens', 'max_completion_tokens'], + fallbacks: [{ name: 'automatic tool choice', applies: error => forced && forcedChoiceRejected(error), apply: () => { forced = false; state.autoToolChoice = true; } }], + build: () => { + const limit = maxTokensParameter(config.model, state.dropped); + return { model: config.model, stream: false, ...chatReasoning(config.model, reviewEffort(config)), ...(limit ? { [limit]: OUTPUT_LIMIT } : {}), + messages: [{ role: 'system', content: library.SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT + (forced ? '' : onlyTool(tool.function.name)) }, + { role: 'user', content }], tools: [tool], parallel_tool_calls: false, + tool_choice: forced ? { type: 'function', function: { name: tool.function.name } } : 'auto' }; + } }); + const reply = await http.json(); + await recordUsage(config.usageDirectory, { raw: reply.usage, model: reply.model ?? config.model, kind: 'review', requestId: reply.id }); + const calls = (reply.choices?.[0]?.message?.tool_calls ?? []).map(call => ({ name: call.function?.name, arguments: call.function?.arguments })); + return { id: reply.id, decision: single(calls, tool.function.name, reply.choices?.[0]?.finish_reason === 'length') }; +} + +async function classifyWithResponses(config, library, tool, content, signal, fetchImpl, state) { + let forced = !state.autoToolChoice; + const efforts = config.policy?.models?.find(entry => entry.id === config.model)?.efforts, effort = reviewEffort(config); + const { http } = await postWithFallback({ fetchImpl, url: responsesEndpoint(config.baseUrl), apiKey: config.apiKey, signal, state, + headers: { 'content-type': 'application/json', authorization: `Bearer ${config.apiKey}` }, + optional: ['reasoning.effort', 'reasoning', 'parallel_tool_calls', 'store', 'max_output_tokens'], + fallbacks: [{ name: 'automatic tool choice', applies: error => forced && forcedChoiceRejected(error), apply: () => { forced = false; state.autoToolChoice = true; } }], + build: () => ({ model: config.model, store: false, max_output_tokens: OUTPUT_LIMIT, + ...(reasons(efforts) && effort ? { reasoning: { effort } } : {}), + instructions: library.SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT + (forced ? '' : onlyTool(tool.function.name)), + input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: content }] }], + tools: [{ type: 'function', name: tool.function.name, description: tool.function.description ?? '', parameters: tool.function.parameters, strict: false }], + parallel_tool_calls: false, tool_choice: forced ? { type: 'function', name: tool.function.name } : 'auto' }) }); + const reply = await http.json(); + await recordUsage(config.usageDirectory, { raw: responsesUsage(reply.usage), model: reply.model ?? config.model, kind: 'review', requestId: reply.id }); + const calls = (reply.output ?? []).filter(item => item.type === 'function_call'); + return { id: reply.id, decision: single(calls, tool.function.name, reply.status === 'incomplete') }; +} + +/** Messages API classification. Forced tool choice is unavailable on current Claude models. */ +async function classifyWithAnthropic(config, library, tool, content, signal, fetchImpl, state) { + const { http } = await postWithFallback({ fetchImpl, url: anthropicEndpoint(config.baseUrl), apiKey: config.apiKey, signal, state, + headers: body => anthropicHeaders(config.apiKey, { body }), optional: ['fallbacks', 'thinking.display', 'output_config'], + build: () => ({ model: config.model, ...anthropicOptions(config.model, { effort: reviewEffort(config) ?? 'low', maxTokens: OUTPUT_LIMIT }), + system: library.SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT + onlyTool(tool.function.name), + messages: [{ role: 'user', content }], tool_choice: { type: 'auto', disable_parallel_tool_use: true }, + tools: [{ name: tool.function.name, description: tool.function.description ?? '', input_schema: tool.function.parameters }] }) }); + const reply = await http.json(); + await recordUsage(config.usageDirectory, { raw: anthropicUsage(reply.usage), model: reply.model ?? config.model, kind: 'review', requestId: reply.id }); + const calls = (reply.content ?? []).filter(block => block.type === 'tool_use').map(block => ({ name: block.name, arguments: block.input })); + return { id: reply.id, decision: single(calls, tool.function.name, reply.stop_reason === 'max_tokens') }; +} + +const CLASSIFIERS = { openai: classifyWithChat, 'openai-responses': classifyWithResponses, anthropic: classifyWithAnthropic }; + +function validate(decision, schema) { + if (!decision || typeof decision !== 'object' || Array.isArray(decision)) throw new ReviewOutputError('Invalid auto-review classification'); + for (const name of schema.required) { + if (typeof decision[name] !== 'string' || !decision[name].trim() || + (schema.properties[name].enum && !schema.properties[name].enum.includes(decision[name]))) + throw new ReviewOutputError(`Invalid auto-review classification field: ${name}`); + } + if (decision.decision === 'BLOCK' && decision.blocked_effect === 'none') + throw new ReviewOutputError('Auto-review returned an inconsistent decision'); + const outbound = ['outbound_or_binding_external_effect', 'data_or_credential_exfiltration'].includes(decision.blocked_effect); + if (decision.decision === 'BLOCK' && outbound && + (decision.outbound_authorization !== 'unauthorized_destination' || !decision.who_sees_it?.trim())) + throw new ReviewOutputError('Auto-review returned an incomplete outbound decision'); + if (decision.proposed_allow_rule !== undefined && typeof decision.proposed_allow_rule !== 'string') + throw new ReviewOutputError('Invalid auto-review proposed rule'); +} /** Use the shipped classifier policy/schema and approval state machine with the configured model. */ export function createLocalClassifier(config, library, { fetchImpl = globalThis.fetch, log = () => {} } = {}) { const tool = library.CLASSIFY_SAND_AUTO_REVIEW_ACTION_TOOL; const schema = tool.function.parameters; + // Parameters a compatible service rejected stay dropped for later reviews. + const state = { dropped: new Set(), autoToolChoice: false }; return { async execute(ctx, args) { const target = args.target?.toJson ? args.target.toJson() : args.target; @@ -20,41 +115,22 @@ export function createLocalClassifier(config, library, { fetchImpl = globalThis. const content = JSON.stringify(input); if (Buffer.byteLength(content) > 1024 * 1024) throw new Error('Auto-review context exceeds the supported size'); const signal = ctx?.signal ? AbortSignal.any([ctx.signal, AbortSignal.timeout(45_000)]) : AbortSignal.timeout(45_000); - const response = await fetchImpl(`${config.baseUrl.replace(/\/$/, '')}/chat/completions`, { - method: 'POST', redirect: 'error', signal, - headers: { 'content-type': 'application/json', authorization: `Bearer ${config.apiKey}` }, - body: JSON.stringify({ model: config.model, stream: false, max_tokens: 4096, - messages: [{ role: 'system', content: library.SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT }, - { role: 'user', content }], tools: [tool], - tool_choice: { type: 'function', function: { name: tool.function.name } }, parallel_tool_calls: false }), - }); - if (!response.ok) { - await response.body?.cancel(); - throw new Error(`Auto-review model returned HTTP ${response.status}`); - } - const reply = await response.json(); - await recordUsage(config.usageDirectory, { raw: reply.usage, model: reply.model ?? config.model, kind: 'review', requestId: reply.id }); - const calls = reply.choices?.[0]?.message?.tool_calls; - if (reply.choices?.[0]?.finish_reason === 'length' || calls?.length !== 1 || calls[0].function?.name !== tool.function.name) - throw new Error('Auto-review model did not return one complete classification'); - let decision; - try { decision = JSON.parse(calls[0].function.arguments); } - catch { throw new Error('Auto-review model returned invalid JSON'); } - if (!decision || typeof decision !== 'object' || Array.isArray(decision)) throw new Error('Invalid auto-review classification'); - for (const name of schema.required) { - if (typeof decision[name] !== 'string' || !decision[name].trim() || - (schema.properties[name].enum && !schema.properties[name].enum.includes(decision[name]))) - throw new Error(`Invalid auto-review classification field: ${name}`); + const classify = CLASSIFIERS[config.apiFormat] ?? classifyWithChat; + let replyId, decision; + // A malformed answer is retried once; service errors and cancellation are not. + for (let attempt = 1; ; attempt++) { + try { + ({ id: replyId, decision } = await classify(config, library, tool, content, signal, fetchImpl, state)); + validate(decision, schema); + break; + } catch (error) { + const retry = error instanceof ReviewOutputError && attempt < 2 && !signal.aborted; + log(`Local auto-review ${retry ? 'retrying after' : 'failed'}: ${error.message}; model=${config.model}`); + if (!retry) throw error; + } } - if (decision.decision === 'BLOCK' && decision.blocked_effect === 'none') - throw new Error('Auto-review returned an inconsistent decision'); - const outbound = ['outbound_or_binding_external_effect', 'data_or_credential_exfiltration'].includes(decision.blocked_effect); - if (decision.decision === 'BLOCK' && outbound && - (decision.outbound_authorization !== 'unauthorized_destination' || !decision.who_sees_it?.trim())) - throw new Error('Auto-review returned an incomplete outbound decision'); const proposedRule = decision.proposed_allow_rule; - if (proposedRule !== undefined && typeof proposedRule !== 'string') throw new Error('Invalid auto-review proposed rule'); - log(`Local auto-review ${decision.decision}; model=${config.model}; request=${String(reply.id ?? 'unavailable').slice(0, 128)}`); + log(`Local auto-review ${decision.decision}; model=${config.model}; request=${String(replyId ?? 'unavailable').slice(0, 128)}`); return new library.SmartModeClassifierResult({ result: { case: 'success', value: { decision: decision.decision === 'ALLOW' ? 1 : 2, ...(decision.decision === 'BLOCK' ? { blockReason: decision.reason.slice(0, 500) } : {}), diff --git a/host/runtime/host-computers.mjs b/host/runtime/host-computers.mjs index 398b9f388422782f3d6b1ca2afb5ca0493f4756a..4fe9f847942e90730443e04a1c65a07bbc5b763d 100644 --- a/host/runtime/host-computers.mjs +++ b/host/runtime/host-computers.mjs @@ -8,7 +8,7 @@ export function observeHostComputers(bridge, { send, intervalMs = 5000 } = {}) { try { const computers = bridge.userComputers.list().map(({ id, label, connected }) => ({ id, label, connected: connected === true, - platform: id.startsWith('mac-') ? 'darwin' : 'unknown', + platform: id.startsWith('mac-') ? 'darwin' : id.startsWith('win-') ? 'win32' : 'unknown', capabilities: ['exec', 'files'], })); send({ type: 'local-computers', available: true, computers }); diff --git a/host/runtime/host-extensions.mjs b/host/runtime/host-extensions.mjs index 20e0e6d40b9f30b5a3f62fba53126d99255d6bf5..096389296a877cb459ee3d901223f4cc722ee58f 100644 --- a/host/runtime/host-extensions.mjs +++ b/host/runtime/host-extensions.mjs @@ -8,6 +8,7 @@ import { startLocalAutoReview } from './host-auto-review.mjs'; import { localTemplates } from './host-local-profile.mjs'; import { createModelRouter } from './model-router.mjs'; import { recordUsage } from './usage-ledger.mjs'; +import { recordRouting } from './routing-log.mjs'; import { transcribeLocalAudio } from './host-speech.mjs'; import { createLocalCapabilities, startLocalMemory } from './host-capabilities.mjs'; import { contextPolicyFor } from './context-policy.mjs'; @@ -15,6 +16,7 @@ import { startLocalManagedSkills } from './host-skills.mjs'; import { startLocalWebhooks } from './host-webhooks.mjs'; import { startLocalFederation } from './host-federation.mjs'; import { createLocalServiceRuntime } from './media-runtime.mjs'; +import { modelRouteForAgent } from './model-routing.mjs'; const unsubscribe = () => () => {}; export function unavailable(capability) { @@ -49,7 +51,13 @@ function localIdentity() { }; } -function inference(config, library, services) { +function inferenceAgentId(options) { + const id = options?.agentId ?? options?.getAgentId?.() ?? options?.agentStore?.getId?.(); + return typeof id === 'string' && id ? id : undefined; +} + +export function createInference(config, library, services, { fetchImpl, sessionFactory = createModelSession } = {}) { + const modelFetch = fetchImpl ?? globalThis.fetch; return { isReady: async () => true, port: { @@ -58,11 +66,20 @@ function inference(config, library, services) { videoAnalysisEnabled: services.videoAnalysisEnabled, createSession: (onRequestId, options) => ['watchVideo', 'videoReview'].includes(options?.localMediaKind) && services.videoAnalysisEnabled(options.localMediaKind) ? services.createVideoSession(options.localMediaKind, onRequestId) - : createModelSession({ ...config, ...contextPolicyFor(config, config.model), onRequestId, - selectRequest: createModelRouter(options?.isSummarizationSession && config.policy ? { ...config, policy: { ...config.policy, mode: 'manual' } } : config, { onDecision: decision => console.info('[model-router]', JSON.stringify(decision)) }), - onUsage: usage => recordUsage(config.usageDirectory, { ...usage, kind: options?.isSummarizationSession ? 'summary' : 'chat' }), - fetchImpl: observeModelFetch(globalThis.fetch, options), - mapError: createHarnessModelErrorMapper(library) }), + : (() => { + const agentId = inferenceAgentId(options); + const route = config.modelRouting ? modelRouteForAgent(config.modelRouting, agentId) : undefined; + const sessionConfig = route ? { ...config, ...route } : { ...config, ...contextPolicyFor(config, config.model) }; + const routerConfig = !config.modelRouting && options?.isSummarizationSession && config.policy + ? { ...config, policy: { ...config.policy, mode: 'manual' } } : config; + return sessionFactory({ ...sessionConfig, onRequestId, + selectRequest: createModelRouter(routerConfig, { agentId, onDecision: decision => console.info('[model-router]', JSON.stringify(decision)) }), + onFallback: event => recordRouting(config.routingDirectory, { kind: 'model-fallback', status: 'fallback', agentId, + session: options?.isSummarizationSession ? 'summary' : 'chat', ...event }), + onUsage: usage => recordUsage(config.usageDirectory, { ...usage, kind: options?.isSummarizationSession ? 'summary' : 'chat' }), + fetchImpl: observeModelFetch(modelFetch, options), + mapError: createHarnessModelErrorMapper(library) }); + })(), // These are official analytics endpoints, disabled with Host telemetry. recordPostTurnLabeling() {}, recordFollowupLabeling() {}, }, @@ -83,7 +100,7 @@ export function createExtensionStarter(library, modelConfig) { 'managed-setup': startLocalManagedSkills, 'bot-template-share': () => localTemplates(), 'remote-agent-messaging': context => startLocalFederation(context, { extensions: id => apis.get(id) }), - inference: () => inference(modelConfig, library, services), + inference: () => createInference(modelConfig, library, services), mcp: context => startLocalHostMcp(context, library, { nativeEnabled: () => capabilities.get().macComputer, permission: () => apis.get('local-tool-permission') }), 'auto-review': context => startLocalAutoReview(context, library, modelConfig), diff --git a/host/runtime/host-network.mjs b/host/runtime/host-network.mjs index 81137e76fc29e60a98392fd9d161a7190961595a..9216c2db00b9e29d6bcd09ec0f9392e7f8b8d660 100644 --- a/host/runtime/host-network.mjs +++ b/host/runtime/host-network.mjs @@ -4,9 +4,10 @@ import http2 from 'node:http2'; import { syncBuiltinESMExports } from 'node:module'; /** Host background services may reach only local endpoints and the configured model. */ -export function installHostNetworkBoundary(modelBaseUrl, { additionalHosts = [] } = {}) { - const modelHost = new URL(modelBaseUrl).hostname; - const allowedHosts = new Set(['127.0.0.1', 'localhost', '::1', '[::1]', modelHost, ...additionalHosts]); +export function installHostNetworkBoundary(modelBaseUrls, { additionalHosts = [] } = {}) { + const values = Array.isArray(modelBaseUrls) ? modelBaseUrls : [modelBaseUrls]; + const modelHosts = values.filter(Boolean).map(value => new URL(value).hostname); + const allowedHosts = new Set(['127.0.0.1', 'localhost', '::1', '[::1]', ...modelHosts, ...additionalHosts]); const assertAllowed = input => { const url = typeof input === 'string' || input instanceof URL ? new URL(input) : input instanceof Request ? new URL(input.url) : null; diff --git a/host/runtime/host-resources.mjs b/host/runtime/host-resources.mjs new file mode 100644 index 0000000000000000000000000000000000000000..51e359866d808b0e5d39cb03da3e56f13152d2a1 --- /dev/null +++ b/host/runtime/host-resources.mjs @@ -0,0 +1,24 @@ +import { lstat, readlink, readdir, rename, symlink, unlink } from 'node:fs/promises'; +import { basename, dirname, join, resolve } from 'node:path'; +import { randomUUID } from 'node:crypto'; + +// Only links pointing into a sibling image-owned Host revision may be replaced. +export function previousImageLink(target, originalDir, name) { + const revision = dirname(dirname(target)); + return basename(originalDir) === 'sand-host' && /^host-[0-9a-f]+$/.test(basename(dirname(originalDir))) && + dirname(revision) === dirname(dirname(originalDir)) && /^host-[0-9a-f]+$/.test(basename(revision)) && + target === join(revision, 'sand-host', name) && target !== join(originalDir, name); +} + +export async function provisionResources(stateDir, originalDir) { + for (const entry of await readdir(originalDir, { withFileTypes: true })) { + if (['host-main.cjs', 'package.json', 'sand-eval-runner.cjs'].includes(entry.name)) continue; + const dst = join(stateDir, entry.name), src = join(originalDir, entry.name); + const existing = await lstat(dst).catch(error => { if (error.code !== 'ENOENT') throw error; }); + if (!existing) { await symlink(src, dst, entry.isDirectory() ? 'dir' : 'file'); continue; } + if (!existing.isSymbolicLink() || !previousImageLink(resolve(stateDir, await readlink(dst)), originalDir, entry.name)) continue; + const tmp = `${dst}.${randomUUID()}.tmp`; + await symlink(src, tmp, entry.isDirectory() ? 'dir' : 'file'); + try { await rename(tmp, dst); } catch (error) { await unlink(tmp); throw error; } + } +} diff --git a/host/runtime/host-summarize.mjs b/host/runtime/host-summarize.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bc1d51492ccd11044c0b3492c3ae2f6d4b3351ec --- /dev/null +++ b/host/runtime/host-summarize.mjs @@ -0,0 +1,74 @@ +import { check } from '../server/security.mjs'; + +const AGENT_ID = /^[a-f0-9-]{1,128}$/i; +// The runner requires a nonempty prompt before it asks promptGlue for an action. +// The replacement below discards this value and emits only summarizeAction. +const MANUAL_SUMMARY_PROMPT = 'Local administrator requested a conversation summary.'; + +function unsupported(value, message) { + check(value, 501, message); + return value; +} + +function isRunning(lifecycle, session, agentId) { + return lifecycle.inFlightRunCounts?.has(session) || lifecycle.runningAgentIds?.().has(agentId); +} + +/** + * Run the Harness' native summarizeAction for one idle Bot. This preserves the + * original transcript and lets the normal summary handler persist its checkpoint. + */ +export async function summarizeAgent(host, _library, agentId) { + check(typeof agentId === 'string' && AGENT_ID.test(agentId), 400, 'Bot ID 无效'); + const transcript = host?.transcript; + unsupported(transcript?.listAgentsSync && transcript?.sessions?.resolveBackgroundSession, + '当前 Host 版本不支持手动压缩'); + const agent = transcript.listAgentsSync().find(item => item.id === agentId); + check(agent, 404, 'Bot 不存在'); + check(!agent.isGroup, 400, '暂不支持压缩群组 Bot'); + + const lifecycle = transcript.runLifecycle, registry = transcript.runnerRegistry; + unsupported(lifecycle?.beginSessionRun && lifecycle?.endSessionRun && lifecycle?.enqueueExclusiveRun && registry?.getRunner, + '当前 Host 版本不支持手动压缩'); + // Resolve without activating the Bot in the currently selected client session. + const session = await transcript.sessions.resolveBackgroundSession(agentId); + check(!isRunning(lifecycle, session, agentId), 409, 'Bot 正在运行,请在任务结束后再压缩'); + const runner = registry.getRunner(session); + const promptGlue = runner?.promptGlue; + unsupported(typeof promptGlue?.assembleTurnAction === 'function' && typeof runner?.run === 'function', + '当前 Host 版本不支持手动压缩'); + + let began = false; + try { + // Mark the turn synchronously before queueing it, so a newly sent user + // message is placed after this isolated summary turn instead of racing it. + lifecycle.beginSessionRun(session); + began = true; + await lifecycle.enqueueExclusiveRun(agentId, async () => { + const original = promptGlue.assembleTurnAction; + const assembleSummaryAction = async () => ({ + // The public Host library does not export its generated proto classes. + // The runner immediately redacts this shape and the summarize handler + // deliberately ignores the empty action payload. + action: { action: { case: 'summarizeAction', value: {} } }, + }); + promptGlue.assembleTurnAction = assembleSummaryAction; + try { + const result = await runner.run(MANUAL_SUMMARY_PROMPT, { + hidden: true, + requestSource: 'event', + advanceChainOnDelivery: false, + }); + check(!result?.aborted && !result?.pausedForUpgrade, 409, '上下文压缩被中断,请稍后重试'); + } finally { + // Do not overwrite a newer replacement if a future Harness version + // changes the glue while this run is completing. + if (promptGlue.assembleTurnAction === assembleSummaryAction) promptGlue.assembleTurnAction = original; + } + }, { lane: 'background', source: 'manual-summary' }); + return { ok: true, agentId, status: 'completed' }; + } finally { + if (began) lifecycle.endSessionRun(session); + await transcript.roster?.emitAgentUpdate?.(agentId); + } +} diff --git a/host/runtime/host.mjs b/host/runtime/host.mjs index a11662185036ad5e104291b8bb46f817e3568066..b7e0f65f8238bc1c28fc31fe14c1257f3611ab1a 100644 --- a/host/runtime/host.mjs +++ b/host/runtime/host.mjs @@ -1,5 +1,6 @@ import { createRequire } from 'node:module'; -import { mkdir, readdir, symlink, lstat, writeFile, rename, readFile } from 'node:fs/promises'; +import { mkdir, writeFile, rename, readFile } from 'node:fs/promises'; +import { provisionResources } from './host-resources.mjs'; import { resolve, join } from 'node:path'; import { loadModelConfig } from './config.mjs'; import { createExtensionStarter } from './host-extensions.mjs'; @@ -12,9 +13,12 @@ import { loadExecutionNode, connectExecutionNode } from '../server/execution-nod import { writePrivate } from '../server/storage.mjs'; import { decorateLocalSharingApi } from './sharing-import.mjs'; import { installLocalPromptPolicy } from './prompt-runtime.mjs'; +import { summarizeAgent } from './host-summarize.mjs'; +import { installModelRejectionGuard } from './model-rejection-guard.mjs'; const stateDir = process.env.GROKBOT_STATE_DIR ?? '/research/state'; const originalDir = process.env.GROKBOT_ORIGINAL_HOST ?? '/research/original-host'; +installModelRejectionGuard(); Object.assign(process.env, { SAND_DATA_ROOT: join(stateDir, 'host-data'), SAND_BACKEND_URL: 'http://127.0.0.1:9', @@ -23,17 +27,9 @@ Object.assign(process.env, { SAND_HOST_IN_BOX: '1', SAND_PACKAGED: '1', }); -async function provisionResources() { - await mkdir(process.env.SAND_DATA_ROOT, { recursive: true }); - for (const entry of await readdir(originalDir, { withFileTypes: true })) { - if (['host-main.cjs', 'package.json', 'sand-eval-runner.cjs'].includes(entry.name)) continue; - const destination = join(stateDir, entry.name); - if (await lstat(destination).catch(() => null)) continue; - await symlink(join(originalDir, entry.name), destination, entry.isDirectory() ? 'dir' : 'file'); - } -} - -await provisionResources(); +await mkdir(process.env.SAND_DATA_ROOT, { recursive: true }); +await provisionResources(stateDir, originalDir); +const revision = (await readFile(join(originalDir, 'version'), 'utf8')).trim(); const executionTransport = await connectExecutionNode(await loadExecutionNode(process.env.GROKBOT_DATA_DIR ?? stateDir), process.env.GROKBOT_DATA_DIR ?? stateDir); const executionNode = executionTransport.config; if (executionNode?.enabled) { @@ -48,7 +44,7 @@ if (internalToken !== undefined && !/^[A-Za-z0-9_-]{32,256}$/.test(internalToken const allowedHosts = process.env.GROKBOT_BOX_HOST ? [process.env.GROKBOT_BOX_HOST] : []; if (process.env.GROKBOT_NOTIFICATION_URL) allowedHosts.push(new URL(process.env.GROKBOT_NOTIFICATION_URL).hostname); if (model.policy.mode === 'adaptive') allowedHosts.push('api.typesafe.ai'); -installHostNetworkBoundary(model.baseUrl, { additionalHosts: allowedHosts }); +installHostNetworkBoundary(model.modelBaseUrls ?? model.baseUrl, { additionalHosts: allowedHosts }); const require = createRequire(import.meta.url); const recovered = process.env.GROKBOT_RECOVERED_CORE === '1'; let libraryPath = resolve(stateDir, 'host-library.cjs'), repaired; @@ -60,7 +56,7 @@ const library = require(libraryPath); const core = recovered ? await loadRecoveredHostCore(library, repaired.directory) : { mode: 'bundled' }; if (recovered) core.reliability = repaired.status; library.activateHostLocale(); -const prompts = await installLocalPromptPolicy(process.env.GROKBOT_DATA_DIR ?? stateDir, library); +const prompts = await installLocalPromptPolicy(process.env.GROKBOT_DATA_DIR ?? stateDir, library, { revision }); const host = new library.SandHost({ startExtensions: createExtensionStarter(library, model) }); let gateway, computers; let stopping = false; @@ -93,8 +89,12 @@ process.once('SIGINT', () => void stop('SIGINT')); try { await host.start(); computers = observeHostComputers(host.getLocalExecBridge()); + const localApplicationRpc = args => { + if (args?.action === 'grokbot.manual-summary') return summarizeAgent(host, library, args.agentId); + return host.requireHostExtensions().api('mcp').applicationRpc(args); + }; gateway = await library.startGatewayServer({ - api: decorateLocalSharingApi({ api: { ...withLibraryCleanup(host.getApi(), host, library), localApplicationRpc: args => host.requireHostExtensions().api('mcp').applicationRpc(args) }, host }), subscribe: listener => host.subscribe(listener), + api: decorateLocalSharingApi({ api: { ...withLibraryCleanup(host.getApi(), host, library), localApplicationRpc }, host }), subscribe: listener => host.subscribe(listener), getHealth: () => host.getHealth(), startedAt: host.startedAt, host: process.env.GROKBOT_HOST_BIND ?? '0.0.0.0', port: Number(process.env.GROKBOT_HOST_PORT ?? 1340), ...(internalToken ? { authToken: internalToken } : {}), @@ -116,7 +116,7 @@ try { onCommandError: report => host.reportGatewayCommandError(report), onCommandComplete: report => host.reportGatewayCommandSuccess(report), }); - const status = { ready: true, revision: 'd0a4baa', model: model.model, pid: process.pid, + const status = { ready: true, revision, model: model.model, pid: process.pid, port: gateway.port, dataRoot: process.env.SAND_DATA_ROOT, identity: 'local-workspace', officialAccount: false, officialBackend: false, telemetry: false, updates: false, core }; await saveHostStatus(status); diff --git a/host/runtime/media-services.mjs b/host/runtime/media-services.mjs index 91fdfab0a01525f412b417250f198e854d673444..84e2045159f86429ccec5b77edacc84026046583 100644 --- a/host/runtime/media-services.mjs +++ b/host/runtime/media-services.mjs @@ -52,7 +52,7 @@ export class MediaServices { check(['image', 'video'].includes(kind), 400, 'Invalid media generation kind'); if (jobId) check(typeof jobId === 'string' && /^[0-9a-f-]{36}$/.test(jobId), 400, 'Invalid media job'); const { model, provider } = await this.resolve(kind, input.model); - const body = mediaInput(model, input), inputHash = digest(JSON.stringify({ kind, model: model.id, body })); + const body = mediaInput(model, input, provider.adapter), inputHash = digest(JSON.stringify({ kind, model: model.id, body })); if (kind === 'image') check((body.n ?? 1) === 1 && (body.max_images ?? 1) === 1 && (body.num_images ?? 1) === 1, 400, 'Configure one image per GenerateImage request'); const requestKey = requestId ? digest(String(requestId)) : randomUUID(); diff --git a/host/runtime/model-common.mjs b/host/runtime/model-common.mjs new file mode 100644 index 0000000000000000000000000000000000000000..03ebe7cd433fd091734868fd5ad2182ead69b3a4 --- /dev/null +++ b/host/runtime/model-common.mjs @@ -0,0 +1,395 @@ +// Shared pieces of the three model API formats: errors, SSE, media, reasoning +// provenance and optional-parameter fallback. +import { recordToolCallOrder } from './reliability/tool-order.mjs'; + +export class ModelRequestError extends Error { + constructor(message, { status, code, retryAfterMs, cause, param } = {}) { + super(message, { cause }); + this.name = 'ModelRequestError'; + this.status = status; + this.code = code; + this.retryAfterMs = retryAfterMs; + this.param = param; + } +} + +export function retryAfterMs(headers) { + const value = headers?.get('retry-after')?.trim(); + if (!value) return undefined; + if (/^\d+(?:\.\d+)?$/.test(value)) { + const milliseconds = Number(value) * 1000; + return Number.isFinite(milliseconds) ? milliseconds : undefined; + } + // HTTP-date is the other Retry-After form; reject numeric-looking invalid values. + if (!/[a-z]/i.test(value)) return undefined; + const deadline = Date.parse(value); + return Number.isFinite(deadline) ? Math.max(0, deadline - Date.now()) : undefined; +} + +/** Build a ModelRequestError from an OpenAI- or Anthropic-style error payload. */ +export function providerError(payload, status, headers, apiKey) { + const error = payload?.error ?? payload?.response?.error ?? payload; + let message = typeof error?.message === 'string' ? error.message : `Model request failed${status ? ` (HTTP ${status})` : ''}`; + // Redact echoed credentials; very short values would only corrupt the message. + if (apiKey && apiKey.length >= 8) message = message.split(apiKey).join('[redacted]'); + const reportedStatus = error?.status ?? error?.status_code; + const code = typeof error?.code === 'string' || typeof error?.code === 'number' ? error.code + : typeof error?.type === 'string' && error.type !== 'error' ? error.type : undefined; + return new ModelRequestError(message, { + status: status ?? (Number.isInteger(reportedStatus) && reportedStatus >= 400 && reportedStatus <= 599 ? reportedStatus : undefined), + code, param: typeof error?.param === 'string' ? error.param : undefined, retryAfterMs: retryAfterMs(headers), + }); +} + +const MAX_ERROR_BODY_BYTES = 64 * 1024; + +export async function errorFromResponse(http, apiKey) { + if (!http.body) return providerError(undefined, http.status, http.headers, apiKey); + const reader = http.body.getReader(); + let bytes, size = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value.byteLength > MAX_ERROR_BODY_BYTES - size) { + await reader.cancel().catch(() => {}); + return new ModelRequestError(`Model request failed (HTTP ${http.status}); error body exceeds 64 KiB`, + { status: http.status, retryAfterMs: retryAfterMs(http.headers) }); + } + // One bounded buffer also handles arbitrarily fragmented or compressed error responses. + if (value.byteLength) { + bytes ??= Buffer.allocUnsafe(MAX_ERROR_BODY_BYTES); + bytes.set(value, size); + size += value.byteLength; + } + } + } finally { + reader.releaseLock(); + } + let payload; + if (size) { + try { payload = JSON.parse(new TextDecoder().decode(bytes.subarray(0, size))); } + catch (error) { if (!(error instanceof SyntaxError)) throw error; } + } + return providerError(payload, http.status, http.headers, apiKey); +} + +const direct = action => action(); +const MAX_EVENT_CHARS = 16 * 1024 * 1024; + +/** SSE events can cross UTF-8 chunks and use LF, CRLF, or CR line endings. */ +export async function* readSse(body, { waitForIO = direct, maxEventChars = MAX_EVENT_CHARS } = {}) { + if (!body) throw new ModelRequestError('Model response has no body'); + const reader = body.getReader(); + const decoder = new TextDecoder('utf-8', { fatal: true }); + let line = '', skipLF = false, data = [], buffered = 0; + function accept(line) { + if (line === '') { + const event = data.length ? data.join('\n') : undefined; + data = []; buffered = 0; + return event; + } + if (line === 'data' || line.startsWith('data:')) { + if (buffered + line.length + 1 > maxEventChars) throw new ModelRequestError('Model SSE event exceeds size limit'); + data.push(line.slice(line[5] === ' ' ? 6 : 5)); + buffered += line.length + 1; + } + return undefined; + } + // Some compatible gateways omit blank lines between data frames. Parse glued + // JSON incrementally so a large event is scanned once, not once per chunk. + let glued; + function resetGlued() { glued = undefined; } + function gluedEvents() { + const events = []; + while (line.startsWith('data:')) { + if (!glued) glued = { start: 0, scan: 0, depth: 0, quoted: false, escaped: false, doneFrom: 0 }; + let start = glued.start || 5; + while (line[start] === ' ' || line[start] === '\t') start++; + if (start !== glued.start) glued.start = glued.start || 5; + if (!glued.doneFrom) glued.doneFrom = start; + const doneToken = '[DONE]'; + if (line.startsWith(doneToken, start)) { + const end = start + doneToken.length; + // A terminal frame may omit its blank-line separator at EOF, but do not + // consume a longer literal value that merely starts with [DONE]. + if (line.length === end || line.startsWith('data:', end)) { + events.push(doneToken); line = line.slice(end); resetGlued(); continue; + } + break; + } + if (!['{', '['].includes(line[start])) break; + let { scan, depth, quoted, escaped } = glued; + if (!scan) { scan = start; depth = 0; quoted = false; escaped = false; } + for (; scan < line.length; scan++) { + const character = line[scan]; + if (quoted) { + if (escaped) escaped = false; + else if (character === '\\') escaped = true; + else if (character === '"') quoted = false; + } else if (character === '"') quoted = true; + else if (character === '{' || character === '[') depth++; + else if ((character === '}' || character === ']') && --depth === 0) { + scan++; + events.push(line.slice(start, scan)); + line = line.slice(scan); + glued = undefined; + break; + } + } + if (glued) { + Object.assign(glued, { scan, depth, quoted, escaped }); + if (line.length - start > maxEventChars) throw new ModelRequestError('Model SSE event exceeds size limit'); + break; + } + } + return events; + } + try { + while (true) { + const { value, done } = await waitForIO(() => reader.read()); + const chunk = done ? decoder.decode() : decoder.decode(value, { stream: true }); + let start = !done && skipLF && chunk[0] === '\n' ? 1 : 0; + skipLF = false; + const breaks = /\r\n|\r|\n/g; + breaks.lastIndex = start; + let match; + while ((match = breaks.exec(chunk))) { + line += chunk.slice(start, match.index); + start = breaks.lastIndex; + if (!done && match[0] === '\r' && start === chunk.length) skipLF = true; + const event = accept(line); + line = ''; resetGlued(); + if (event !== undefined) yield event; + breaks.lastIndex = start; + } + // `done` only flushes the decoder; EOF alone is not an SSE separator. + if (done) break; + line += chunk.slice(start); + for (const event of gluedEvents()) yield event; + if (line.length > maxEventChars) throw new ModelRequestError('Model SSE event exceeds size limit'); + // EOF alone is not an SSE separator. Only the explicitly supported glued + // frame form above may complete without a normal blank line. + } + } finally { + await reader.cancel().catch(() => {}); + reader.releaseLock(); + } +} + +export function parseEvent(data) { + try { return JSON.parse(data); } + catch (cause) { throw new ModelRequestError('Invalid JSON in model SSE event', { cause }); } +} + +function bytesToBase64(value) { + const bytes = value instanceof ArrayBuffer ? Buffer.from(value) : Buffer.from(value.buffer, value.byteOffset, value.byteLength); + return bytes.toString('base64'); +} + +/** An image or file part as an http(s) URL or a data URL. */ +export function mediaUrl(part, fallbackType = 'image/png') { + const value = part.image ?? part.data ?? part.url; + const mimeType = part.mimeType ?? fallbackType; + if (value instanceof URL) return mediaUrl({ ...part, image: value.href }, fallbackType); + if (typeof value === 'string') { + if (/^(https?:\/\/|data:)/i.test(value)) return value; + if (/^[a-z][\w+.-]*:/i.test(value)) throw new TypeError('Unsupported media URL scheme'); + if (!value.trim()) throw new TypeError('Media content is empty'); + return `data:${mimeType};base64,${value}`; + } + if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return `data:${mimeType};base64,${bytesToBase64(value)}`; + throw new TypeError('Media must contain a URL, base64 string, or bytes'); +} + +export function parseDataUrl(url) { + const match = /^data:([^;,]+)?(?:;[^,]*)?;base64,(.*)$/is.exec(url); + return match ? { mediaType: (match[1] ?? 'application/octet-stream').toLowerCase(), data: match[2] } : null; +} + +/** File parts the model APIs read natively: PDFs and plain text. Others become a short note. */ +export function fileKind(part) { + const type = String(part.mimeType ?? '').toLowerCase(); + if (type === 'application/pdf') return 'pdf'; + if (type.startsWith('text/') || ['application/json', 'application/xml'].includes(type)) return 'text'; + if (type.startsWith('image/')) return 'image'; + return 'other'; +} + +export function fileText(part) { + const url = mediaUrl(part, part.mimeType); + const parsed = parseDataUrl(url); + return parsed ? Buffer.from(parsed.data, 'base64').toString('utf8') : url; +} + +export function unsupportedFileNote(part) { + return `[Attached file ${part.filename ?? 'without a name'} (${part.mimeType ?? 'unknown type'}) cannot be read by this model API.]`; +} + +export function textValue(value) { + return typeof value === 'string' ? value : JSON.stringify(value ?? ''); +} + +/** OpenAI-compatible providers reject empty or overlong function names. */ +export const validFunctionName = value => typeof value === 'string' && value.length > 0 && value.length <= 128; + +export function messageParts(message) { + return typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content ?? []; +} + +export const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']; + +/** An explicit level from the policy or router; 'default' and 'auto' mean the model default. */ +export function explicitEffort(effort) { + return EFFORT_ORDER.includes(effort) ? effort : undefined; +} + +/** + * Reasoning produced here is tagged with its API format and model. cursor.* mirrors the + * original Harness convention (it summarizes and replays by modelName); grokbot.* lets + * each format replay only reasoning it can read. + */ +export function reasoningProviderOptions({ format, model, providerId, summarized = false, itemId, emptyThinking = false }) { + return { cursor: { modelName: model, ...(summarized ? { isAlreadySummarizedThinking: true } : {}) }, + grokbot: { format, model, ...(providerId ? { providerId } : {}), ...(itemId ? { itemId } : {}), ...(emptyThinking ? { emptyThinking: true } : {}) } }; +} + +export function reasoningOrigin(part) { + const own = part.providerOptions?.grokbot ?? part.experimental_providerMetadata?.grokbot; + const cursor = part.providerOptions?.cursor ?? part.experimental_providerMetadata?.cursor; + return { format: own?.format, model: own?.model ?? cursor?.modelName, providerId: own?.providerId, itemId: own?.itemId, + summarized: cursor?.isAlreadySummarizedThinking === true, phase: own?.phase, emptyThinking: own?.emptyThinking === true }; +} + +/** + * Optional request parameters some compatible gateways reject. When a 400 names one of + * them, the session removes it and retries; the decision is kept for later turns. + */ +export function rejectedOption(error, candidates) { + if (error?.status !== 400) return undefined; + const message = String(error.message ?? ''), param = error.param ?? ''; + if (param) return candidates.find(name => param === name || param.startsWith(`${name}.`) || param.startsWith(`${name}[`)); + return candidates.find(name => new RegExp(`(^|[^\\w.])${name.replace(/[.[\]]/g, '\\$&')}(?![\\w])`).test(message)); +} + +export function deletePath(object, path) { + const keys = path.split('.'); + let target = object; + for (const key of keys.slice(0, -1)) { + if (!target || typeof target !== 'object') return; + target = target[key]; + } + if (target && typeof target === 'object') delete target[keys.at(-1)]; + if (keys.length > 1) { + const parent = keys.slice(0, -1).reduce((value, key) => value?.[key], object); + if (parent && typeof parent === 'object' && !Object.keys(parent).length) deletePath(object, keys.slice(0, -1).join('.')); + } +} + +/** + * POST with bounded retries. Drop a named, rejected option before considering a + * fallback that changes conversation history (replayed reasoning or inline images). + */ +export async function postWithFallback({ fetchImpl, url, headers, build, signal, apiKey, optional = [], state, fallbacks = [], + waitForIO = direct, log = message => console.warn(message) }) { + for (let attempt = 0; ; attempt++) { + signal?.throwIfAborted(); + const body = build(); + for (const name of state.dropped) deletePath(body, name); + const http = await waitForIO(() => fetchImpl(url, { method: 'POST', headers: typeof headers === 'function' ? headers(body) : headers, + body: JSON.stringify(body), signal, redirect: 'error' })); + if (http.ok) return { http, body }; + const error = await waitForIO(() => errorFromResponse(http, apiKey)); + signal?.throwIfAborted(); + if (attempt < 6) { + const option = rejectedOption(error, optional.filter(name => !state.dropped.has(name) && + name.split('.').reduce((value, key) => value?.[key], body) !== undefined)); + if (option) { state.dropped.add(option); log(`[model] ${new URL(url).host}: retrying without ${option}`); continue; } + const fallback = fallbacks.find(item => !item.used && item.applies(error, body)); + if (fallback) { fallback.used = true; fallback.apply(); log(`[model] ${new URL(url).host}: ${fallback.name ?? 'fallback'} after HTTP ${error.status ?? 'error'}`); continue; } + } + throw error; + } +} + +/** A 400 about reasoning that was replayed from an earlier turn. */ +export function replayRejected(error) { + // Gateways join words with underscores (native_thinking_replay_mismatch): no word boundaries. + return error?.status === 400 && /signature|thinking|encrypted|reasoning/i.test(`${error.message ?? ''} ${error.code ?? ''}`); +} + +function plainUserDelivery(call) { + const args = call?.args; + if (call?.type !== 'tool-call' || call.toolName !== 'SendToUser' || args?.type !== 'text' || + typeof args.content !== 'string' || !args.content || Object.keys(args).length !== 2) return undefined; + return args.content; +} + +// A fresh provider ID does not prove fresh work. Inspect only the immediately preceding +// successful exchange, never search across user turns, other tools or conversations. +function isRepeatedDelivery(calls, messages) { + if (calls.length !== 1 || !messages || messages.length < 2) return false; + const text = plainUserDelivery(calls[0]); + if (text === undefined) return false; + const receipt = messages.at(-1), previous = messages.at(-2); + if (receipt?.role !== 'tool' || previous?.role !== 'assistant' || + receipt.providerOptions?.cursor?.highLevelToolCallResult?.isError !== false) return false; + const parts = messageParts(receipt), sent = messageParts(previous).filter(part => part.type === 'tool-call'); + return parts.length === 1 && sent.length === 1 && plainUserDelivery(sent[0]) === text && + parts[0].type === 'tool-result' && parts[0].toolName === 'SendToUser' && !parts[0].isError && + Boolean(sent[0].toolCallId) && parts[0].toolCallId === sent[0].toolCallId && receipt.id === sent[0].toolCallId; +} + +export function* streamToolCalls(calls, messages, signal) { + if (new Set(calls.map(call => call.toolCallId)).size !== calls.length) throw new ModelRequestError('Duplicate model tool call ID'); + if (isRepeatedDelivery(calls, messages)) { + throw new ModelRequestError('The model requested the same text that was already delivered. Stopped this turn before sending it again.', + { code: 'repeated_user_delivery' }); + } + const discard = recordToolCallOrder(calls); + let handedOff = 0; + const discardUnhanded = () => { + for (let i = handedOff; i < calls.length; i++) discard(calls[i].toolCallId); + }; + signal?.addEventListener('abort', discardUnhanded, { once: true }); + try { + for (const call of calls) { + // The Harness consumes one argument stream at a time; serialize parallel calls. + yield { type: 'tool-call-streaming-start', toolCallId: call.toolCallId, toolName: call.toolName }; + yield { type: 'tool-call-delta', toolCallId: call.toolCallId, toolName: call.toolName, argsTextDelta: JSON.stringify(call.args) }; + handedOff++; + yield call; + } + } finally { + // Already delivered calls still need their ordering entries until journal execution. + signal?.removeEventListener('abort', discardUnhanded); + discardUnhanded(); + } +} + +export function serializeToolCalls(calls) { + return [...streamToolCalls(calls)]; +} + +/** + * Arguments of a model tool call. Compatible endpoints send no argument text for a call without + * parameters; that means {} only for a tool that requires none, so lost arguments are never run as {}. + */ +export function parseToolArguments(name, text, tools) { + if (text === undefined || (typeof text === 'string' && !text.trim())) { + const tool = tools?.find(item => item?.name === name); + const required = (tool?.parameters?.jsonSchema ?? tool?.parameters)?.required; + if (tool && !(Array.isArray(required) && required.length)) return {}; + } + try { return JSON.parse(text); } + catch (cause) { throw new ModelRequestError(`Invalid tool arguments for ${name}`, { cause }); } +} + +/** JSON Schema of a Harness tool. */ +export function toolSchema(tool) { + if (tool.type === 'provider-defined' || tool.customToolFormat) throw new TypeError('This session supports JSON function tools only'); + if (typeof tool.name !== 'string' || !tool.name) throw new TypeError('Tool name is required'); + const parameters = tool.parameters?.jsonSchema ?? tool.parameters; + if (!parameters || typeof parameters !== 'object') throw new TypeError('Tool schema is required'); + return { name: tool.name, description: tool.description ?? '', parameters }; +} diff --git a/host/runtime/model-errors.mjs b/host/runtime/model-errors.mjs index 26a9d3ee7f22f3b575e3dcb46b182a338bbfc044..fc5a47eaead3a15d5b5389568cf5915a9a2bbe19 100644 --- a/host/runtime/model-errors.mjs +++ b/host/runtime/model-errors.mjs @@ -3,7 +3,7 @@ import { ModelRequestError } from './model-session.mjs'; const CONFIG_CODES = new Set(['invalid_api_key', 'authentication_error']); const TERMINAL_CODES = new Set([ 'invalid_request_error', 'model_not_found', 'permission_denied', 'insufficient_quota', - 'content_filter', 'length', + 'content_filter', 'length', 'repeated_user_delivery', ]); const TERMINAL_STATUSES = new Set([400, 402, 403, 404, 405, 413, 415, 422]); const RATE_LIMIT_CODES = new Set(['rate_limit_error', 'rate_limit_exceeded']); @@ -21,6 +21,11 @@ export function createHarnessModelErrorMapper(library) { const status = error.status; const code = typeof error.code === 'string' ? error.code : undefined; const options = { cause: error, displayInfo: { detail: error.message, isRetryable: false } }; + // Quota exhaustion is permanent until the account changes. Unlike a transient + // 429, sending the same request again only creates a restart/retry storm. + const quotaExhausted = code === 'API_KEY_QUOTA_EXHAUSTED' || code === 'insufficient_quota' || + (status === 402 && !code) || + /(?:api[ _-]?key|account)\s+(?:quota|credit|balance)\s+(?:is\s+)?(?:exhausted|used up|depleted|exceeded)|(?:账户|账户余额|API\s*额度|额度)\s*(?:已)?\s*(?:用完|耗尽|不足)/i.test(error.message); const inputLimit = ['context_length_exceeded', 'input_token_limit_exceeded', 'prompt_too_long'].includes(code) || ([400, 413, 422].includes(status) && /(?:maximum context length|input token limit|prompt (?:is )?too long|context window.*exceed)/i.test(error.message)); if (inputLimit && typeof InputTokenLimitError === 'function') { @@ -30,11 +35,11 @@ export function createHarnessModelErrorMapper(library) { // This is a local provider API key, so official-account login is not the remedy. return new ActionRequiredError(error.message, 'config', options); } - if (TERMINAL_STATUSES.has(status) || TERMINAL_CODES.has(code)) { + if (quotaExhausted || TERMINAL_STATUSES.has(status) || TERMINAL_CODES.has(code)) { return new NonRetriableError(error.message, options); } const rateLimited = status === 429 || RATE_LIMIT_CODES.has(code); - const unavailable = status === 503; + const unavailable = status === 503 || status === 529 || code === 'overloaded_error'; if (rateLimited || unavailable || (status >= 500 && status <= 599 && error.retryAfterMs !== undefined)) { const metadata = new Headers(); if (Number.isFinite(error.retryAfterMs) && error.retryAfterMs >= 0) { diff --git a/host/runtime/model-observation.mjs b/host/runtime/model-observation.mjs index 407a49c628a4924a82c45be50851be45c441bfd0..c7c9d1519cabbc8f0c8994fa3dd7866a41bc7837 100644 --- a/host/runtime/model-observation.mjs +++ b/host/runtime/model-observation.mjs @@ -14,7 +14,7 @@ export function observeModelFetch(fetchImpl, session = {}, stateDir = process.en await mkdir(directory, { recursive: true, mode: 0o700 }); const body = JSON.parse(options.body); const messages = []; - for (const message of body.messages) { + for (const message of body.messages ?? body.input ?? []) { if (message.role === 'tool') { messages.push({ role: 'tool', tool_call_id: message.tool_call_id, content: message.content }); } else if (message.role === 'assistant' && message.tool_calls?.length) { @@ -35,7 +35,7 @@ export function observeModelFetch(fetchImpl, session = {}, stateDir = process.en } capture = { directory, record: { at: new Date().toISOString(), sessionId, requestedModel: session.modelId, inferenceReason: session.inferenceReason, - model: body.model, tools: body.tools?.map(tool => tool.function.name), messages } }; + model: body.model, tools: body.tools?.map(tool => tool.function?.name ?? tool.name), messages } }; } catch (error) { if (error.code !== 'ENOENT') console.error(`[model-observation] ${error.message}`); } diff --git a/host/runtime/model-policy.mjs b/host/runtime/model-policy.mjs index 7a271fc78021c7c13dd58223550e097ceb40cf1b..c8e1b1b3188180bd99df3f3823149d464bc0044f 100644 --- a/host/runtime/model-policy.mjs +++ b/host/runtime/model-policy.mjs @@ -1,9 +1,40 @@ import { validateContextPolicy } from './context-policy.mjs'; +import { chatReasoning } from './openai-chat.mjs'; +import { claudeTraits } from './anthropic-messages.mjs'; export const TIERS = ['routine', 'reasoning', 'expert']; -export const EFFORTS = ['none', 'low', 'medium', 'high', 'xhigh', 'max']; +export const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']; + +function catalogCapacity(value) { + return Number.isSafeInteger(value) && value > 0 && value <= 100_000_000 ? value : undefined; +} + +function summaryThreshold(contextWindowTokens) { + if (contextWindowTokens < 2) return 0; + return Math.max(1, Math.floor(contextWindowTokens * 0.75 / 1_000) * 1_000); +} + +/** Recommended compaction settings for a model chosen from a provider catalog. */ +export function catalogContextPolicy(model, reportedCapacity) { + const capacity = catalogCapacity(reportedCapacity); + if (capacity) return { contextWindowTokens: capacity, summaryThresholdTokens: summaryThreshold(capacity), contextSource: 'provider' }; + return { contextWindowTokens: 0, summaryThresholdTokens: 0, contextSource: 'unknown' }; +} + +/** Reference levels for well-known model families; a provider catalog overrides them. */ export function effortLevels(model) { - if (/deepseek-v4/i.test(model)) return ['none', 'low', 'high', 'max']; - if (/claude-(opus|sonnet)-5-5/i.test(model)) return ['low', 'medium', 'high', 'xhigh', 'max']; + const id = String(model).toLowerCase(); + if (/deepseek-v4/.test(id)) return ['none', 'low', 'high', 'max']; + if (/^claude-/.test(id)) { + const traits = claudeTraits(id); + if (!traits.known) return []; + // 'none' turns thinking off where the model allows it. + return [...(traits.disable === 'never' ? [] : ['none']), ...traits.efforts, ...(traits.budget && !traits.efforts.length ? ['low', 'medium', 'high'] : [])]; + } + if (/^o[134](?:-|$)/.test(id)) return ['low', 'medium', 'high']; + if (/^gpt-5(?:-mini|-nano)?$/.test(id)) return ['minimal', 'low', 'medium', 'high']; + if (/^gpt-5\.1/.test(id)) return ['none', 'low', 'medium', 'high']; + if (/^gpt-5\.[2-9]/.test(id)) return ['none', 'low', 'medium', 'high', 'xhigh']; + if (/^grok-4/.test(id)) return ['minimal', 'low', 'medium', 'high', 'xhigh']; return []; } export function defaultPolicy(model = 'deepseek-v4.1-flash') { @@ -43,8 +74,7 @@ export function validatePolicy(value, model) { if (typeof classifierModel !== 'string' || !/^jev-[a-zA-Z0-9._-]{1,80}$/.test(classifierModel)) fail('Invalid classifier model'); return { mode: policy.mode, effort, models, routes, classifierModel }; } +/** OpenAI Chat reasoning parameters; other formats map the level themselves. */ export function reasoningOptions(model, effort) { - if (!effort || effort === 'default') return {}; - return { reasoning_effort: effort, - ...(/deepseek/i.test(model) ? { thinking: { type: effort === 'none' ? 'disabled' : 'enabled' } } : {}) }; + return chatReasoning(model, effort); } diff --git a/host/runtime/model-rejection-guard.mjs b/host/runtime/model-rejection-guard.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8f44d169da9af18fbcca5ad61891c51c5d93ded4 --- /dev/null +++ b/host/runtime/model-rejection-guard.mjs @@ -0,0 +1,27 @@ +// The recovered Harness can leave a rejected model-stream branch unobserved +// after it has already turned the same failure into the current turn result. +function modelFailureDetails(reason) { + for (let current = reason, depth = 0; current && depth < 5; current = current.cause, depth++) { + if (current?.name === 'ModelRequestError') { + return { name: current.name, status: current.status, code: current.code }; + } + } + return undefined; +} + +export function isContainedModelRejection(reason) { + return modelFailureDetails(reason) !== undefined; +} + +export function installModelRejectionGuard(target = process) { + target.on('unhandledRejection', reason => { + const failure = modelFailureDetails(reason); + if (failure) { + // The request has its own error path; never include provider text or credentials in process logs. + console.error(`[local-host] contained unhandled model rejection ${JSON.stringify(failure)}`); + return; + } + // Attaching this listener changes Node's default rejection policy, so preserve it for unrelated defects. + throw reason; + }); +} diff --git a/host/runtime/model-router.mjs b/host/runtime/model-router.mjs index b0265456ab0cd4dad6943c66068deaba9455483b..04a9b931a34762c82a992e3e186ceeb856addbc5 100644 --- a/host/runtime/model-router.mjs +++ b/host/runtime/model-router.mjs @@ -3,9 +3,10 @@ import { createHash } from 'node:crypto'; import { TIERS, reasoningOptions, validatePolicy } from './model-policy.mjs'; import { recordUsage } from './usage-ledger.mjs'; import { contextPolicyFor } from './context-policy.mjs'; +import { modelRouteForAgent } from './model-routing.mjs'; const effortCriteria = { - none: 'No deliberate reasoning is needed.', low: 'Quick, straightforward reasoning is enough.', + none: 'No deliberate reasoning is needed.', minimal: 'Only a brief check is needed.', low: 'Quick, straightforward reasoning is enough.', medium: 'Several dependent reasoning steps are needed.', high: 'Substantial analysis or difficult debugging is needed.', xhigh: 'Very challenging reasoning across interacting constraints is needed.', max: 'Exceptionally difficult research, proofs or novel algorithmic reasoning justifies maximum effort.', @@ -46,7 +47,17 @@ export async function classifyTask({ apiKey, model = 'jev-latest', state, policy })); return { difficulty: answer.choice, confidence: answer.confidence, efforts, model: data.model ?? model, usage: data.usage }; } -export function createModelRouter(config, { fetchImpl = fetch, onDecision = () => {} } = {}) { +export function createModelRouter(config, { fetchImpl = fetch, onDecision = () => {}, agentId } = {}) { + if (config.modelRouting) { + const route = modelRouteForAgent(config.modelRouting, agentId); + const select = candidate => ({ ...candidate, + requestOptions: reasoningOptions(candidate.model, candidate.effort) }); + const selected = { ...select(route), fallbacks: route.fallbacks.map(select) }; + return async ({ signal } = {}) => { + signal?.throwIfAborted(); + return selected; + }; + } const policy = validatePolicy(config.policy, config.model); let cachedKey, cachedDecision; return async ({ messages, signal }) => { diff --git a/host/runtime/model-routing.mjs b/host/runtime/model-routing.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f06aaed4cc7ee72fa3671b542b683b035a2f7cf6 --- /dev/null +++ b/host/runtime/model-routing.mjs @@ -0,0 +1,261 @@ +// Versioned model-provider configuration and deterministic Bot route resolution. +// Credentials stay in model.env; callers of publicModelRouting never receive them. +import { validateContextPolicy } from './context-policy.mjs'; +import { EFFORTS, effortLevels } from './model-policy.mjs'; + +export const API_FORMATS = Object.freeze(['openai', 'openai-responses', 'anthropic']); +export const MODEL_ROUTING_ENV = 'GROKBOT_MODEL_ROUTING'; + +const MAX_PROVIDERS = 32; +const MAX_PROFILES = 128; +const MAX_BOT_ROUTES = 512; +const MAX_FALLBACKS = 8; +const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/; +const AGENT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/; + +const plainObject = value => value !== null && typeof value === 'object' && !Array.isArray(value); +const fail = message => { throw new TypeError(message); }; + +function text(value, label, maximum = 256) { + if (typeof value !== 'string' || !value.trim() || value.length > maximum || /[\r\n\0]/.test(value)) + fail(`Invalid ${label}`); + return value.trim(); +} + +function identifier(value, label = 'ID') { + const id = text(value, label, 64); + if (!ID.test(id)) fail(`Invalid ${label}`); + return id; +} + +function endpoint(value) { + let url; + try { url = new URL(text(value, 'Base URL', 2048)); } + catch { fail('Invalid Base URL'); } + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) + fail('Invalid Base URL'); + return url.href.replace(/\/$/, ''); +} + +function key(value) { + return text(value, 'API Key', 8192); +} + +function modelId(value) { + return text(value, 'model ID', 256); +} + +function levels(value, model) { + if (value === undefined) return effortLevels(model); + if (!Array.isArray(value) || value.some(item => !EFFORTS.includes(item))) fail('Invalid effort levels'); + return EFFORTS.filter(level => value.includes(level)); +} + +function profileContext(value) { + try { return validateContextPolicy(value); } + catch (error) { fail(error.message); } +} + +function contextForProfile(value, previous) { + const hasContext = Object.prototype.hasOwnProperty.call(value, 'contextWindowTokens'); + const hasThreshold = Object.prototype.hasOwnProperty.call(value, 'summaryThresholdTokens'); + // A provider catalog is optional. Never invent a capacity: it would make the + // Harness defer compaction past the actual context limit of an unknown model. + const defaults = previous ?? {}; + return profileContext({ + contextWindowTokens: hasContext ? value.contextWindowTokens : (defaults.contextWindowTokens ?? 0), + summaryThresholdTokens: hasThreshold ? value.summaryThresholdTokens : (defaults.summaryThresholdTokens ?? 0), + }); +} + +function routeEffort(value, profile) { + const effort = value ?? 'default'; + if (effort !== 'default' && !profile.efforts.includes(effort)) fail(`Unsupported effort for ${profile.id}`); + return effort; +} + +function normalizeProvider(value, previousProviders) { + if (!plainObject(value)) fail('Invalid provider'); + const id = identifier(value.id, 'provider ID'); + const apiFormat = value.apiFormat; + if (!API_FORMATS.includes(apiFormat)) fail('Invalid API format'); + const supplied = typeof value.apiKey === 'string' && value.apiKey.trim() ? key(value.apiKey) : undefined; + const apiKey = supplied ?? previousProviders.get(id)?.apiKey; + if (!apiKey) fail(`API Key is required for ${id}`); + return { id, name: text(value.name, 'provider name', 120), apiFormat, baseUrl: endpoint(value.baseUrl), apiKey }; +} + +/** Validate one provider draft, retaining its existing credential when its stable ID is unchanged. */ +export function validateModelProvider(input, { previous } = {}) { + const previousProviders = new Map((previous?.providers ?? []).map(item => [item.id, item])); + return normalizeProvider(input, previousProviders); +} + +function normalizeRoute(value, profiles, label) { + if (!plainObject(value)) fail(`Invalid ${label}`); + const profileId = identifier(value.profileId, `${label} profile ID`); + const primary = profiles.get(profileId); + if (!primary) fail(`Unknown profile: ${profileId}`); + const effort = routeEffort(value.effort, primary); + const rawFallbacks = value.fallbacks ?? []; + if (!Array.isArray(rawFallbacks) || rawFallbacks.length > MAX_FALLBACKS) fail(`Invalid ${label} fallbacks`); + const seen = new Set([profileId]); + const fallbacks = rawFallbacks.map((item, index) => { + if (!plainObject(item)) fail(`Invalid ${label} fallback`); + const fallbackProfileId = identifier(item.profileId, `${label} fallback profile ID`); + if (seen.has(fallbackProfileId)) fail(`Duplicate ${label} fallback profile`); + seen.add(fallbackProfileId); + const profile = profiles.get(fallbackProfileId); + if (!profile) fail(`Unknown profile: ${fallbackProfileId}`); + return { profileId: fallbackProfileId, effort: routeEffort(item.effort, profile), order: index }; + }); + return { profileId, effort, fallbacks }; +} + +/** A usable empty draft for a new installation. It is intentionally not a persisted config. */ +export function emptyModelRouting() { + return { version: 1, providers: [], profiles: [], defaultRoute: null, botRoutes: {} }; +} + +/** Convert the old, single-provider environment shape into an editable draft. */ +export function legacyModelRouting(legacy = {}) { + const apiFormat = API_FORMATS.includes(legacy.apiFormat) ? legacy.apiFormat : 'openai'; + const baseUrl = typeof legacy.baseUrl === 'string' ? legacy.baseUrl : ''; + const apiKey = typeof legacy.apiKey === 'string' ? legacy.apiKey : ''; + const model = typeof legacy.model === 'string' ? legacy.model : ''; + if (!baseUrl && !apiKey && !model) return emptyModelRouting(); + const models = legacy.policy?.models; + const previous = Array.isArray(models) ? models.find(item => item?.id === model) : undefined; + const profile = model ? { + id: 'default', name: '默认模型', providerId: 'default', model, + efforts: Array.isArray(previous?.efforts) ? previous.efforts.filter(level => EFFORTS.includes(level)) : effortLevels(model), + ...profileContext({ contextWindowTokens: previous?.contextWindowTokens ?? legacy.contextWindowTokens ?? 0, + summaryThresholdTokens: previous?.summaryThresholdTokens ?? 0 }), + } : null; + const provider = (baseUrl || apiKey || profile) ? { id: 'default', name: '默认服务', apiFormat, baseUrl, apiKey } : null; + return { version: 1, providers: provider ? [provider] : [], profiles: profile ? [profile] : [], + defaultRoute: provider && profile ? { profileId: profile.id, effort: legacy.policy?.effort ?? 'default', fallbacks: [] } : null, + botRoutes: {} }; +} + +/** Parse a persisted JSON routing configuration. Missing JSON means legacy configuration. */ +export function parseModelRouting(value, legacy) { + if (!value) return { config: legacyModelRouting(legacy), migrated: true }; + let parsed; + try { parsed = JSON.parse(value); } + catch { fail('Invalid multi-provider model configuration'); } + return { config: validateModelRouting(parsed), migrated: false }; +} + +/** + * Validate a configuration received from the admin API. Empty API key fields retain + * the credential for a provider with the same stable ID; a newly added provider needs one. + */ +export function validateModelRouting(input, { previous } = {}) { + if (!plainObject(input) || input.version !== 1) fail('Unsupported model routing configuration'); + if (!Array.isArray(input.providers) || !input.providers.length || input.providers.length > MAX_PROVIDERS) + fail('Invalid providers'); + if (!Array.isArray(input.profiles) || !input.profiles.length || input.profiles.length > MAX_PROFILES) + fail('Invalid model profiles'); + const providerIds = new Set(); + const providers = input.providers.map(item => { + const provider = validateModelProvider(item, { previous }); + const { id } = provider; + if (providerIds.has(id)) fail('Duplicate provider ID'); + providerIds.add(id); + return provider; + }); + const providersById = new Map(providers.map(item => [item.id, item])); + const previousProfiles = new Map((previous?.profiles ?? []).map(item => [item.id, item])); + const profileIds = new Set(); + const profiles = input.profiles.map(item => { + if (!plainObject(item)) fail('Invalid model profile'); + const id = identifier(item.id, 'profile ID'); + if (profileIds.has(id)) fail('Duplicate profile ID'); + profileIds.add(id); + const providerId = identifier(item.providerId, 'provider ID'); + if (!providersById.has(providerId)) fail(`Unknown provider: ${providerId}`); + const model = modelId(item.model); + const context = contextForProfile(item, previousProfiles.get(id)); + return { id, name: text(item.name, 'profile name', 120), providerId, model, efforts: levels(item.efforts, model), ...context }; + }); + const profilesById = new Map(profiles.map(item => [item.id, item])); + const defaultRoute = normalizeRoute(input.defaultRoute, profilesById, 'default route'); + if (input.botRoutes !== undefined && !plainObject(input.botRoutes)) fail('Invalid Bot routes'); + const entries = Object.entries(input.botRoutes ?? {}); + if (entries.length > MAX_BOT_ROUTES) fail('Too many Bot routes'); + const botRoutes = {}; + for (const [agentId, route] of entries) { + if (!AGENT_ID.test(agentId)) fail('Invalid Bot ID'); + botRoutes[agentId] = normalizeRoute(route, profilesById, `Bot route ${agentId}`); + } + return { version: 1, providers, profiles, defaultRoute, botRoutes }; +} + +/** Safe form for administration API responses. */ +export function publicModelRouting(config) { + return { + version: 1, + providers: (config.providers ?? []).map(({ apiKey, ...provider }) => ({ ...provider, hasApiKey: Boolean(apiKey) })), + profiles: (config.profiles ?? []).map(profile => ({ ...profile, efforts: [...profile.efforts] })), + defaultRoute: config.defaultRoute ? structuredClone(config.defaultRoute) : null, + botRoutes: structuredClone(config.botRoutes ?? {}), + }; +} + +function candidate(profile, provider, route) { + return { + profileId: profile.id, profileName: profile.name, providerId: provider.id, providerName: provider.name, + apiFormat: provider.apiFormat, baseUrl: provider.baseUrl, apiKey: provider.apiKey, + model: profile.model, efforts: [...profile.efforts], effort: route.effort, + contextWindowTokens: profile.contextWindowTokens, summaryThresholdTokens: profile.summaryThresholdTokens, + }; +} + +function routeContext(candidates) { + const capacities = candidates.map(item => item.contextWindowTokens).filter(value => value > 0); + const contextWindowTokens = capacities.length ? Math.min(...capacities) : 0; + const thresholds = candidates.map(item => item.summaryThresholdTokens) + .filter(value => value > 0 && (!contextWindowTokens || value < contextWindowTokens)); + return { contextWindowTokens, summaryThresholdTokens: thresholds.length ? Math.min(...thresholds) : 0 }; +} + +/** Resolve the configured direct route for a Bot. The returned values include private transport details. */ +export function modelRouteForAgent(config, agentId) { + const profiles = new Map(config.profiles.map(item => [item.id, item])); + const providers = new Map(config.providers.map(item => [item.id, item])); + const botRoute = agentId && config.botRoutes?.[agentId]; + const route = botRoute ?? config.defaultRoute; + if (!route) fail('No default model route'); + const resolve = item => { + const profile = profiles.get(item.profileId); + const provider = profile ? providers.get(profile.providerId) : undefined; + if (!profile || !provider) fail(`Invalid configured profile: ${item.profileId}`); + return candidate(profile, provider, item); + }; + const primary = resolve(route); + const fallbacks = route.fallbacks.map(resolve); + return { ...primary, fallbacks, routeSource: botRoute ? 'bot' : 'default', agentId: agentId || undefined, + ...routeContext([primary, ...fallbacks]) }; +} + +/** Resolve one profile for catalog and connection tests without its route fallback chain. */ +export function modelRouteForProfile(config, profileId, { effort = 'default' } = {}) { + const profiles = new Map(config.profiles.map(item => [item.id, item])); + const providers = new Map(config.providers.map(item => [item.id, item])); + const id = identifier(profileId, 'profile ID'); + const profile = profiles.get(id); + const provider = profile ? providers.get(profile.providerId) : undefined; + if (!profile || !provider) fail(`Unknown profile: ${id}`); + const route = { profileId: id, effort: routeEffort(effort, profile), fallbacks: [] }; + return { ...candidate(profile, provider, route), fallbacks: [], routeSource: 'profile', ...routeContext([candidate(profile, provider, route)]) }; +} + +export function isConfiguredModelRouting(config) { + try { + const route = modelRouteForAgent(config); + return Boolean(route.baseUrl && route.apiKey && route.model); + } catch { + return false; + } +} diff --git a/host/runtime/model-session.mjs b/host/runtime/model-session.mjs index b97707490cce3fa963ca56a5513b9a366ca51461..5a43fb91cf9bec62d154cc3372f35fe03afab780 100644 --- a/host/runtime/model-session.mjs +++ b/host/runtime/model-session.mjs @@ -1,183 +1,139 @@ +// Model session for the original Harness: one streamed turn per call, in the configured +// API format. Formats share request selection, cancellation, usage and completion. import { randomUUID } from 'node:crypto'; +import { ModelRequestError } from './model-common.mjs'; +import { chatEndpoint, chatTurn, convertChatMessages, convertChatTools } from './openai-chat.mjs'; +import { responsesEndpoint, responsesTurn } from './openai-responses.mjs'; +import { anthropicEndpoint, anthropicTurn } from './anthropic-messages.mjs'; +export { ModelRequestError }; export const SUPPORTED_MODELS = Object.freeze([ 'deepseek-flash', 'deepseek-v4.1-flash', 'deepseek-v4.1-flash-sg', ]); +export const API_FORMATS = Object.freeze(['openai', 'openai-responses', 'anthropic']); -export class ModelRequestError extends Error { - constructor(message, { status, code, retryAfterMs, cause } = {}) { - super(message, { cause }); - this.name = 'ModelRequestError'; - this.status = status; - this.code = code; - this.retryAfterMs = retryAfterMs; - } +/** Translate the original Harness CoreMessage representation (OpenAI Chat) without losing screenshots. */ +export const convertMessages = messages => convertChatMessages(messages); +export const convertTools = convertChatTools; + +const FORMATS = { + openai: { endpoint: chatEndpoint, turn: chatTurn }, + 'openai-responses': { endpoint: responsesEndpoint, turn: responsesTurn }, + anthropic: { endpoint: baseUrl => anthropicEndpoint(baseUrl), turn: anthropicTurn }, +}; + +function deferred() { + let resolve, reject; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + // Consumers read several promises after fullStream; reject all without unhandled rejections. + promise.catch(() => {}); + return { promise, resolve, reject }; } -function retryAfterMs(headers) { - const value = headers?.get('retry-after')?.trim(); - if (!value) return undefined; - if (/^\d+(?:\.\d+)?$/.test(value)) { - const milliseconds = Number(value) * 1000; - return Number.isFinite(milliseconds) ? milliseconds : undefined; - } - // HTTP-date is the other Retry-After form; reject numeric-looking invalid values. - if (!/[a-z]/i.test(value)) return undefined; - const deadline = Date.parse(value); - return Number.isFinite(deadline) ? Math.max(0, deadline - Date.now()) : undefined; +function abortError(reason) { + return reason instanceof Error ? reason : new DOMException('Model stream was canceled', 'AbortError'); } -function imageUrl(part) { - const value = part.image ?? part.data ?? part.url; - if (value instanceof URL) return imageUrl({ ...part, image: value.href }); - if (typeof value === 'string') { - if (/^(https?:\/\/|data:image\/)/i.test(value)) return value; - if (/^[a-z][\w+.-]*:/i.test(value)) throw new TypeError('Unsupported image URL scheme'); - if (!value.trim()) throw new TypeError('Image content is empty'); - return `data:${part.mimeType ?? 'image/png'};base64,${value}`; - } - if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) { - const bytes = value instanceof ArrayBuffer ? Buffer.from(value) - : Buffer.from(value.buffer, value.byteOffset, value.byteLength); - return `data:${part.mimeType ?? 'image/png'};base64,${bytes.toString('base64')}`; - } - throw new TypeError('Image must contain a URL, base64 string, or bytes'); +// Arm a deadline only while waiting for upstream I/O, never while paused at a yield. +function ioDeadline(controller, ms) { + const { signal } = controller; + return async action => { + signal.throwIfAborted(); + let onAbort; + const canceled = new Promise((_, reject) => { + onAbort = () => reject(signal.reason); + signal.addEventListener('abort', onAbort, { once: true }); + }); + const timer = setTimeout(() => controller.abort(new DOMException(`Model upstream idle for ${ms} ms`, 'TimeoutError')), ms); + timer.unref(); + try { return await Promise.race([canceled, Promise.resolve().then(() => { signal.throwIfAborted(); return action(); })]); } + finally { clearTimeout(timer); signal.removeEventListener('abort', onAbort); } + }; } -function textValue(value) { - return typeof value === 'string' ? value : JSON.stringify(value ?? ''); +function candidateKey(candidate) { + // Stable IDs keep provider URLs and credentials out of adaptation state and logs. + return candidate.profileId ?? `${candidate.apiFormat}\n${candidate.baseUrl}\n${candidate.model}`; } -/** Translate the original Harness CoreMessage representation without losing screenshots. */ -export function convertMessages(messages) { - const output = []; - let toolImages = []; - const flushToolImages = () => { - if (!toolImages.length) return; - output.push({ role: 'user', content: [ - { type: 'text', text: 'Screenshots from the preceding tool results:' }, ...toolImages, - ] }); - toolImages = []; +function requestCandidate(value, defaults) { + const candidate = { + baseUrl: value?.baseUrl ?? defaults.baseUrl, + apiKey: value?.apiKey ?? defaults.apiKey, + apiFormat: value?.apiFormat ?? defaults.apiFormat, + model: value?.model ?? defaults.model, + effort: value?.effort ?? defaults.effort, + efforts: value?.efforts ?? defaults.efforts, + requestOptions: value?.requestOptions ?? defaults.requestOptions, + contextWindowTokens: value?.contextWindowTokens ?? defaults.contextWindowTokens, + summaryThresholdTokens: value?.summaryThresholdTokens ?? defaults.summaryThresholdTokens, + profileId: value?.profileId ?? defaults.profileId, + profileName: value?.profileName ?? defaults.profileName, + providerId: value?.providerId ?? defaults.providerId, + providerName: value?.providerName ?? defaults.providerName, }; - for (const message of messages) { - if (message.role !== 'tool') flushToolImages(); - const parts = typeof message.content === 'string' - ? [{ type: 'text', text: message.content }] : message.content ?? []; - if (message.role === 'tool') { - for (const part of parts) { - if (part.type !== 'tool-result' || !part.toolCallId) { - throw new TypeError('Tool messages require tool-result parts and toolCallId'); - } - const extra = part.experimental_content ?? []; - const fallback = extra.filter(p => p.type === 'text').map(p => p.text).join('\n'); - output.push({ role: 'tool', tool_call_id: part.toolCallId, - content: part.result === undefined ? fallback : textValue(part.result) }); - toolImages.push(...extra.filter(p => p.type === 'image').map(p => ({ - type: 'image_url', image_url: { url: imageUrl(p) }, - }))); - } - } else if (message.role === 'assistant') { - const content = parts.filter(p => p.type === 'text').map(p => p.text).join(''); - const reasoning = parts.filter(p => p.type === 'reasoning').map(p => p.text).join(''); - const calls = parts.filter(p => p.type === 'tool-call').map(p => ({ - id: p.toolCallId, type: 'function', - function: { name: p.toolName, arguments: textValue(p.args ?? {}) }, - })); - output.push({ role: 'assistant', content: content || (calls.length ? null : ''), - ...(reasoning ? { reasoning_content: reasoning } : {}), - ...(calls.length ? { tool_calls: calls } : {}) }); - } else if (['user', 'system', 'developer'].includes(message.role)) { - const content = parts.map(part => { - if (part.type === 'text') return { type: 'text', text: part.text }; - if (part.type === 'image' && message.role === 'user') { - return { type: 'image_url', image_url: { url: imageUrl(part) } }; - } - throw new TypeError(`Unsupported ${message.role} content type: ${part.type}`); - }); - output.push({ role: message.role, content: content.every(p => p.type === 'text') - ? content.map(p => p.text).join('') : content }); - } else { - throw new TypeError(`Unsupported message role: ${message.role}`); - } + if (typeof candidate.baseUrl !== 'string' || !candidate.baseUrl || + (candidate.apiKey !== undefined && typeof candidate.apiKey !== 'string') || + typeof candidate.model !== 'string' || !candidate.model.trim() || + !FORMATS[candidate.apiFormat]) { + throw new TypeError('selected model must include a configured provider, format, and model'); } - flushToolImages(); - return output; + return candidate; } -export function convertTools(tools = []) { - return tools.map(tool => { - if (tool.type === 'provider-defined' || tool.customToolFormat) { - throw new TypeError('This session supports JSON function tools only'); - } - if (typeof tool.name !== 'string' || !tool.name) throw new TypeError('Tool name is required'); - const parameters = tool.parameters?.jsonSchema ?? tool.parameters; - if (!parameters || typeof parameters !== 'object') throw new TypeError('Tool schema is required'); - return { type: 'function', function: { - name: tool.name, description: tool.description ?? '', parameters, - } }; - }); +function quotaExhausted(error) { + const code = typeof error?.code === 'string' ? error.code : ''; + if (code === 'API_KEY_QUOTA_EXHAUSTED' || code === 'insufficient_quota') return true; + // A bare 402 is a balance error, but a 429 or a model-specific quota + // message can be temporary and must remain retryable. + if (error?.status === 402 && !code) return true; + return /(?:api[ _-]?key|account)\s+(?:quota|credit|balance)\s+(?:is\s+)?(?:exhausted|used up|depleted|exceeded)|(?:账户|账户余额|API\s*额度|额度)\s*(?:已)?\s*(?:用完|耗尽|不足)/i.test(error?.message ?? ''); } -function deferred() { - let resolve, reject; - const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); - // Consumers read several promises after fullStream; reject all without unhandled rejections. - promise.catch(() => {}); - return { promise, resolve, reject }; +function retryableFailure(error, { controller, upstreamSignal, idleTimedOut }) { + if (controller.signal.aborted || upstreamSignal?.aborted) return idleTimedOut(); + if (error?.name === 'TimeoutError') return true; + if (error?.name === 'AbortError') return false; + if (error?.status === 408 || error?.status === 402 || error?.status === 429 || + (Number.isInteger(error?.status) && error.status >= 500 && error.status <= 599)) return true; + if (Number.isInteger(error?.status) || error instanceof ModelRequestError) return false; + return error?.name === 'TypeError' || ['ECONNABORTED', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTUNREACH', + 'ENETUNREACH', 'ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_SOCKET'].includes(error?.code); } -function abortError(reason) { - return reason instanceof Error ? reason : new DOMException('Model stream was canceled', 'AbortError'); +function distinctCredentialCandidates(candidates, { exhausted = false } = {}) { + if (!exhausted) return candidates; + const keys = new Set(); + return candidates.filter(candidate => { + // A fallback sharing a key has the same quota and cannot recover an exhausted account. + if (keys.has(candidate.apiKey)) return false; + keys.add(candidate.apiKey); + return true; + }); } -/** SSE events can cross UTF-8 chunks and use LF, CRLF, or CR line endings. */ -async function* readSse(body) { - if (!body) throw new ModelRequestError('Model response has no body'); - const reader = body.getReader(); - const decoder = new TextDecoder(); - let pending = '', data = []; - function accept(line) { - if (line === '') { - const event = data.length ? data.join('\n') : undefined; - data = []; - return event; - } - if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, '')); - return undefined; - } - try { - while (true) { - const { value, done } = await reader.read(); - pending += done ? decoder.decode() : decoder.decode(value, { stream: true }); - let match; - while ((match = /\r\n|\r|\n/.exec(pending))) { - if (!done && match[0] === '\r' && match.index === pending.length - 1) break; - const line = pending.slice(0, match.index); - pending = pending.slice(match.index + match[0].length); - const event = accept(line); - if (event !== undefined) yield event; - } - if (done) { - if (pending) accept(pending); - const event = accept(''); - if (event !== undefined) yield event; - break; - } - } - } finally { - await reader.cancel().catch(() => {}); - reader.releaseLock(); - } +function skippedCredentialCandidates(candidates) { + const keys = new Set(); + return candidates.filter(candidate => { + const duplicate = keys.has(candidate.apiKey); + keys.add(candidate.apiKey); + return duplicate; + }); +} + +function publicCandidate(candidate) { + return { profileId: candidate.profileId, profileName: candidate.profileName, + providerId: candidate.providerId, providerName: candidate.providerName, + apiFormat: candidate.apiFormat, model: candidate.model }; } -function endpointFor(baseUrl) { - const url = new URL(baseUrl); - if (!['http:', 'https:'].includes(url.protocol)) throw new TypeError('baseUrl must use HTTP or HTTPS'); - url.pathname = url.pathname.replace(/\/+$/, ''); - if (!url.pathname.endsWith('/chat/completions')) url.pathname += '/chat/completions'; - return url.href; +function compactionCapabilities({ contextWindowTokens, summaryThresholdTokens }) { + if (!Number.isSafeInteger(contextWindowTokens) || !Number.isSafeInteger(summaryThresholdTokens) || + summaryThresholdTokens <= 0 || summaryThresholdTokens >= contextWindowTokens) return {}; + return { supportsSelfSummary: true, earlyCompactionContextTokenThreshold: summaryThresholdTokens }; } +/** Usage arrives normalized to OpenAI Chat fields from every format. */ function usageValues(raw = {}, contextWindowTokens = 0) { const count = value => Number.isFinite(value) && value >= 0 ? value : 0; const inputTokens = count(raw.prompt_tokens), outputTokens = count(raw.completion_tokens); @@ -190,32 +146,35 @@ function usageValues(raw = {}, contextWindowTokens = 0) { }; } -export function createModelSession({ baseUrl, apiKey, model, onRequestId, +export function createModelSession({ baseUrl, apiKey, model, onRequestId, apiFormat = 'openai', policy, fetchImpl = globalThis.fetch, headers = {}, requestOptions = {}, contextWindowTokens = 0, - summaryThresholdTokens = 0, mapError = error => error, onUsage = async () => {}, selectRequest } = {}) { + summaryThresholdTokens = 0, mapError = error => error, onUsage = async () => {}, selectRequest, + onFallback = async () => {}, idleTimeoutMs = 300_000, profileId, providerId, efforts } = {}) { if (typeof model !== 'string' || !model.trim() || model !== model.trim() || model.length > 256 || /[\r\n\0]/.test(model)) { throw new TypeError('model must be an explicitly selected, nonempty model ID'); } if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function'); if (typeof mapError !== 'function') throw new TypeError('mapError must be a function'); + if (!Number.isInteger(idleTimeoutMs) || idleTimeoutMs < 1 || idleTimeoutMs > 2_147_483_647) { + throw new TypeError('idleTimeoutMs must be a positive timer interval'); + } if (!Number.isSafeInteger(contextWindowTokens) || contextWindowTokens < 0) { throw new TypeError('contextWindowTokens must be a nonnegative integer'); } - const endpoint = endpointFor(baseUrl); + if (!FORMATS[apiFormat]) throw new TypeError(`apiFormat must be one of ${API_FORMATS.join(', ')}`); + // Adaptive routing may select models with different parameter and replay support. + const adaptations = new Map(); + // Once a fallback accepts a call, keep using it for the rest of this session. + // The Harness opens a session per turn, so the next turn tries the primary + // again. Returning to a primary that expects its own signed thinking within + // the tool loop would make the next step invalid when the fallback stripped it. + let preferredKey; + const defaults = { baseUrl, apiKey, apiFormat, model, requestOptions, contextWindowTokens, + summaryThresholdTokens, profileId, providerId, efforts }; + const effortsFor = id => policy?.models?.find(entry => entry.id === id)?.efforts; let resolvedModelId; let selectedContext = { contextWindowTokens, summaryThresholdTokens }; - function providerError(payload, status, responseHeaders) { - const error = payload?.error ?? payload; - let message = typeof error?.message === 'string' ? error.message : `Model request failed${status ? ` (HTTP ${status})` : ''}`; - if (apiKey) message = message.split(apiKey).join('[redacted]'); - const reportedStatus = error?.status ?? error?.status_code; - return new ModelRequestError(message, { - status: status ?? (Number.isInteger(reportedStatus) && reportedStatus >= 400 && reportedStatus <= 599 - ? reportedStatus : undefined), - code: typeof error?.code === 'string' || typeof error?.code === 'number' ? error.code : undefined, - retryAfterMs: retryAfterMs(responseHeaders), - }); - } + let earlyCompaction; class Executor { constructor(initialMessages, trackModel) { @@ -230,24 +189,44 @@ export function createModelSession({ baseUrl, apiKey, model, onRequestId, const slots = Object.fromEntries(['response', 'usage', 'extendedUsage', 'providerMetadata', 'invocationId'].map(key => [key, deferred()])); const controller = new AbortController(); const signal = ctx?.signal; + const waitForIO = ioDeadline(controller, idleTimeoutMs); let settled = false; const fail = error => { if (settled) return; settled = true; Object.values(slots).forEach(slot => slot.reject(error)); }; - const cancel = () => { - const error = abortError(signal?.reason); - controller.abort(error); - fail(error); - }; - if (signal?.aborted) cancel(); - else signal?.addEventListener('abort', cancel, { once: true }); const messages = this.getMessages(); const trackModel = this.trackModel; async function* produce() { let notified = false; - let recordedUsage, reportedModel = model, reportedId, selectedEffort; + let recordedUsage, reportedModel = model, reportedId, selectedEffort, reportedCandidate; + let usageWrite, usagePending = false; + const attemptUsages = []; + const snapshotUsage = () => { + if (!recordedUsage) return; + attemptUsages.push({ + raw: recordedUsage, + model: reportedModel, + requestId: reportedId, + effort: selectedEffort, + profileId: reportedCandidate?.profileId, + providerId: reportedCandidate?.providerId, + }); + recordedUsage = undefined; + }; + const recordUsage = () => { + snapshotUsage(); + if (!usageWrite || usagePending) { + usagePending = true; + const queued = usageWrite ?? Promise.resolve(); + usageWrite = queued.then(async () => { + for (const usage of attemptUsages.splice(0)) await onUsage(usage); + }).catch(error => console.error(`[usage] ${error.message}`)) + .finally(() => { usagePending = false; }); + } + return usageWrite; + }; const notifyRequest = id => { if (!notified && id) { notified = true; @@ -256,130 +235,166 @@ export function createModelSession({ baseUrl, apiKey, model, onRequestId, }; try { controller.signal.throwIfAborted(); - const functions = convertTools(tools); - const selected = await selectRequest?.({ messages, signal: controller.signal }); - const requestContext = { contextWindowTokens: selected?.contextWindowTokens ?? contextWindowTokens, - summaryThresholdTokens: selected?.summaryThresholdTokens ?? summaryThresholdTokens }; - if (trackModel) selectedContext = requestContext; - const selectedModel = selected?.model ?? model; - reportedModel = selectedModel; selectedEffort = selected?.effort; - const body = { ...requestOptions, ...selected?.requestOptions, model: selectedModel, messages: convertMessages(messages), stream: true, - stream_options: { ...requestOptions.stream_options, include_usage: true }, - ...(functions.length ? { tools: functions } : {}), - ...(options.maxTokens !== undefined ? { max_tokens: options.maxTokens } : {}) }; - // A caller cannot replace the original Harness tool surface through requestOptions. - if (!functions.length) delete body.tools; - const requestHeaders = new Headers(headers); - requestHeaders.set('content-type', 'application/json'); - requestHeaders.set('accept', 'text/event-stream'); - if (apiKey) requestHeaders.set('authorization', `Bearer ${apiKey}`); - const http = await fetchImpl(endpoint, { method: 'POST', headers: requestHeaders, - body: JSON.stringify(body), signal: controller.signal }); - if (!http.ok) { - let payload; - try { payload = await http.json(); } catch { payload = undefined; } - throw providerError(payload, http.status, http.headers); - } - notifyRequest(http.headers.get('x-request-id') ?? http.headers.get('request-id')); - let id, responseModel = selectedModel, created, text = '', reasoning = '', rawUsage = {}; - let finishReason, receivedChoice = false, receivedDone = false; - const toolCalls = new Map(); - for await (const data of readSse(http.body)) { - controller.signal.throwIfAborted(); - if (data.trim() === '[DONE]') { receivedDone = true; break; } - let chunk; - try { chunk = JSON.parse(data); } - catch (cause) { throw new ModelRequestError('Invalid JSON in model SSE event', { cause }); } - if (chunk.error) throw providerError(chunk, undefined, http.headers); - if (chunk.id) { id = chunk.id; reportedId = id; notifyRequest(id); } - if (chunk.model) { responseModel = chunk.model; reportedModel = responseModel; } - if (Number.isFinite(chunk.created)) created = chunk.created; - if (chunk.usage) { rawUsage = { ...rawUsage, ...chunk.usage }; recordedUsage = rawUsage; } - const choice = chunk.choices?.find(item => (item.index ?? 0) === 0); - if (!choice) continue; - receivedChoice = true; - if (choice.finish_reason) finishReason = choice.finish_reason; - const delta = choice.delta ?? {}; - if (typeof delta.reasoning_content === 'string' && delta.reasoning_content) { - reasoning += delta.reasoning_content; - yield { type: 'reasoning', textDelta: delta.reasoning_content }; - } - if (typeof delta.content === 'string' && delta.content) { - text += delta.content; - yield { type: 'text-delta', textDelta: delta.content }; - } - for (const part of delta.tool_calls ?? []) { - const index = part.index ?? 0; - const call = toolCalls.get(index) ?? { id: '', name: '', arguments: '' }; - if (part.id) call.id += part.id; - if (part.function?.name) call.name += part.function.name; - if (part.function?.arguments) call.arguments += part.function.arguments; - toolCalls.set(index, call); + const selected = selectRequest ? await waitForIO(() => selectRequest({ messages, signal: controller.signal })) : undefined; + const requested = requestCandidate(selected, defaults); + const configured = [requested, + ...((selected?.fallbacks ?? []).map(candidate => requestCandidate(candidate, defaults)))]; + const preferredIndex = preferredKey ? configured.findIndex(candidate => candidateKey(candidate) === preferredKey) : -1; + const ordered = preferredIndex > 0 + ? [configured[preferredIndex], ...configured.filter((_, index) => index !== preferredIndex)] + : configured; + const primary = ordered[0]; + let candidates = ordered; + const requestContext = { contextWindowTokens: primary.contextWindowTokens, + summaryThresholdTokens: primary.summaryThresholdTokens }; + if (trackModel) { selectedContext = requestContext; earlyCompaction = undefined; } + let turn; + let activeIterator; + for (let attempt = 0; attempt < candidates.length; attempt++) { + const candidate = candidates[attempt]; + const format = FORMATS[candidate.apiFormat]; + const attemptController = new AbortController(); + const onCancel = () => attemptController.abort(controller.signal.reason); + controller.signal.addEventListener('abort', onCancel, { once: true }); + const attemptSignal = attemptController.signal; + let idleTimedOut = false; + attemptSignal.addEventListener('abort', () => { + if (attemptSignal.reason?.name === 'TimeoutError') idleTimedOut = true; + }, { once: true }); + const attemptWaitForIO = ioDeadline(attemptController, idleTimeoutMs); + const adaptationKey = candidateKey(candidate); + if (!adaptations.has(adaptationKey)) adaptations.set(adaptationKey, { dropped: new Set(), stripReasoning: false, toolImagesAsMessage: false }); + let emittedVisibleOutput = false; + recordedUsage = undefined; + reportedId = undefined; + reportedModel = candidate.model; + selectedEffort = candidate.effort; + reportedCandidate = candidate; + try { + const iterator = format.turn({ fetchImpl, endpoint: format.endpoint(candidate.baseUrl), apiKey: candidate.apiKey, + headers, model: candidate.model, messages, tools, + effort: candidate.effort ?? candidate.requestOptions?.reasoning_effort, + efforts: candidate.efforts ?? effortsFor(candidate.model), maxTokens: options.maxTokens, + requestOptions: candidate.requestOptions, signal: attemptSignal, waitForIO: attemptWaitForIO, + state: adaptations.get(adaptationKey), notifyRequest, + providerId: candidate.providerId, + onModel: value => { reportedModel = value; }, onId: value => { reportedId = value; }, + onUsage: value => { recordedUsage = value; } }); + activeIterator = iterator; + while (true) { + const next = await iterator.next(); + if (next.done) { turn = next.value; break; } + // Reasoning is hidden. A fallback is still safe until text or a tool call escapes. + if (next.value?.type !== 'reasoning') emittedVisibleOutput = true; + yield next.value; + } + activeIterator = undefined; + break; + } catch (error) { + // A cancellation can arrive while onFallback() is still awaiting. Do + // not attach another request to an already-canceled controller. + controller.signal.throwIfAborted(); + if (quotaExhausted(error)) { + const remaining = candidates.slice(attempt); + const skipped = skippedCredentialCandidates(remaining); + candidates = distinctCredentialCandidates(candidates, { exhausted: true }); + const nextDistinct = candidates[attempt + 1]; + if (skipped.length) { + try { + await onFallback({ from: publicCandidate(candidate), to: nextDistinct ? publicCandidate(nextDistinct) : undefined, + attempt: attempt + 1, reason: 'quota', skipped: skipped.map(publicCandidate) }); + } catch (logError) { + console.warn(`[model-session] Unable to record skipped model fallback: ${logError.code ?? logError.name}`); + } + } + } + const next = candidates[attempt + 1]; + if (emittedVisibleOutput || !next || !retryableFailure(error, { + controller: attemptController, upstreamSignal: signal, idleTimedOut: () => idleTimedOut, + })) throw error; + try { + await onFallback({ from: publicCandidate(candidate), to: publicCandidate(next), attempt: attempt + 1, + reason: idleTimedOut ? 'timeout' + : Number.isInteger(error?.status) ? `HTTP ${error.status}` : 'network' }); + } catch (logError) { + console.warn(`[model-session] Unable to record model fallback: ${logError.code ?? logError.name}`); + } + preferredKey = candidateKey(next); + controller.signal.throwIfAborted(); + } finally { + if (activeIterator) { + await activeIterator.return().catch(() => {}); + activeIterator = undefined; + } + controller.signal.removeEventListener('abort', onCancel); + attemptController.abort(); } } + if (!turn) throw new ModelRequestError('All configured model attempts failed'); controller.signal.throwIfAborted(); - if (!receivedChoice || (!receivedDone && !finishReason)) { - throw new ModelRequestError('Model SSE stream ended before a completion marker'); - } - if (finishReason === 'length' || finishReason === 'content_filter') { - throw new ModelRequestError(`Model response stopped with ${finishReason}`, { code: finishReason }); - } - const content = []; - if (reasoning) content.push({ type: 'reasoning', text: reasoning }); - if (text) content.push({ type: 'text', text }); - const calls = [...toolCalls.entries()].sort(([a], [b]) => a - b).map(([, call]) => { - if (!call.id || !call.name) throw new ModelRequestError('Incomplete model tool call identity'); - let args; - try { args = JSON.parse(call.arguments || '{}'); } - catch (cause) { throw new ModelRequestError(`Invalid tool arguments for ${call.name}`, { cause }); } - return { type: 'tool-call', toolCallId: call.id, toolName: call.name, args }; - }); - // Original Harness consumes one argument stream at a time; serialize parallel calls. - for (const call of calls) { - const { toolCallId, toolName, args } = call; - yield { type: 'tool-call-streaming-start', toolCallId, toolName }; - yield { type: 'tool-call-delta', toolCallId, toolName, argsTextDelta: JSON.stringify(args) }; - yield call; - content.push(call); - } - const responseId = id ?? randomUUID(); + const responseId = turn.id ?? randomUUID(); notifyRequest(responseId); - const timestamp = created === undefined ? new Date() : new Date(created * 1000); + const timestamp = new Date(); // Harness interprets maxTokens as context capacity, not the output token limit. - const values = usageValues(rawUsage, requestContext.contextWindowTokens); - if (trackModel) resolvedModelId = responseModel; - slots.response.resolve({ id: responseId, timestamp, modelId: responseModel, - messages: [{ id: responseId, role: 'assistant', content }] }); + const values = usageValues(turn.usage, requestContext.contextWindowTokens); + const compaction = compactionCapabilities(requestContext); + if (trackModel) { + resolvedModelId = turn.model; + earlyCompaction = compaction.earlyCompactionContextTokenThreshold === undefined ? undefined : { + threshold: compaction.earlyCompactionContextTokenThreshold, + inputTokens: values.extendedUsage.inputTokens, + }; + } + slots.response.resolve({ id: responseId, timestamp, modelId: turn.model, + messages: [{ id: responseId, role: 'assistant', content: turn.content }], ...compaction }); slots.usage.resolve(values.usage); slots.extendedUsage.resolve(values.extendedUsage); slots.providerMetadata.resolve(undefined); slots.invocationId.resolve(invocationId ?? responseId); settled = true; - yield { type: 'finish', finishReason: calls.length ? 'tool-calls' : (finishReason ?? 'stop'), - usage: values.usage, response: { id: responseId, timestamp, modelId: responseModel } }; + // A consumer may stop on finish without ever asking for the iterator's done step. + signal?.removeEventListener('abort', onAbort); + recordUsage(); + yield { type: 'finish', finishReason: turn.toolCalls ? 'tool-calls' : 'stop', + usage: values.usage, response: { id: responseId, timestamp, modelId: turn.model } }; } catch (error) { - const mapped = mapError(error); + let mapped; + try { mapped = controller.signal.aborted ? controller.signal.reason : mapError(error); } + catch (mappingError) { mapped = mappingError; } fail(mapped); throw mapped; } finally { - if (recordedUsage) { - try { await onUsage({ raw: recordedUsage, model: reportedModel, requestId: reportedId, effort: selectedEffort }); } - catch (error) { console.error(`[usage] ${error.message}`); } - } - signal?.removeEventListener('abort', cancel); + signal?.removeEventListener('abort', onAbort); if (!settled) fail(abortError()); - controller.abort(); + await recordUsage(); } } const iterator = produce(); + let closing; + const cancel = error => { + signal?.removeEventListener('abort', onAbort); + if (!settled) { controller.abort(error); fail(controller.signal.reason); } + }; + const onAbort = () => { + cancel(abortError(signal.reason)); + // A paused consumer need not pull again to unlock the reader and record observed usage. + closing ??= iterator.return().catch(() => {}); + }; + if (signal?.aborted) onAbort(); + else signal?.addEventListener('abort', onAbort, { once: true }); const fullStream = { [Symbol.asyncIterator]() { return this; }, - next: value => iterator.next(value), - return: value => { cancel(); signal?.removeEventListener('abort', cancel); return iterator.return(value); }, - throw: error => { - fail(error); controller.abort(error); signal?.removeEventListener('abort', cancel); - return iterator.throw(error); + async next(value) { + controller.signal.throwIfAborted(); + const step = await iterator.next(value); + controller.signal.throwIfAborted(); + return step; + }, + async return(value) { + cancel(abortError()); + return closing ? await closing : iterator.return(value); }, + throw: error => { cancel(error); return iterator.throw(error); }, }; return { fullStream, ...Object.fromEntries(Object.entries(slots).map(([key, slot]) => [key, slot.promise])) }; } @@ -387,7 +402,7 @@ export function createModelSession({ baseUrl, apiKey, model, onRequestId, return { getModelId: () => model, getResolvedModelId: () => resolvedModelId, - getEarlyCompaction: () => undefined, + getEarlyCompaction: () => earlyCompaction && { ...earlyCompaction }, getLocalContextPolicy: () => ({ ...selectedContext }), getExecutor: state => new Executor(state, true), getExecutorWithoutResolvedModelTracking: state => new Executor(state, false), diff --git a/host/runtime/native-desktop.mjs b/host/runtime/native-desktop.mjs index 57dfb068fad941df6e742e31a23facbb329f5701..74f7194d6c3650380a96bf45536d18f9d4c91609 100644 --- a/host/runtime/native-desktop.mjs +++ b/host/runtime/native-desktop.mjs @@ -21,7 +21,7 @@ export async function createNativeDesktop({ permission, enabled = () => true, re return { list: async () => enabled() ? (await request('tools', {})).computers : [], async call({ scope, machineId, toolId, arguments: args = {}, signal }) { - if (!enabled()) throw new Error('Mac computer control is disabled'); + if (!enabled()) throw new Error('Computer control is disabled'); const grants = typeof permission === 'function' ? permission() : permission; if (!scope?.agentId || !scope.toolCallId || !grants) throw new Error('Computer calls require an agent tool scope'); const epoch = scope.directionEpoch ?? grants.directionEpoch(scope.agentId); @@ -50,7 +50,7 @@ export async function createNativeDesktop({ permission, enabled = () => true, re } return { isError: true, content: [{ type: 'text', text: outcome.status === 'needs_permission' ? 'Allow the computer helper in macOS Accessibility and Screen Recording settings.' - : outcome.status === 'ask' ? 'Approve this application on the target Mac.' : outcome.error || 'Computer action failed' }] }; + : outcome.status === 'ask' ? 'Approve this application on the target computer.' : outcome.error || 'Computer action failed' }] }; }, }; } diff --git a/host/runtime/openai-chat.mjs b/host/runtime/openai-chat.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fb840382bba9eae11a8b8db1d8e2bcaba0a7f3a3 --- /dev/null +++ b/host/runtime/openai-chat.mjs @@ -0,0 +1,175 @@ +// OpenAI Chat Completions format (OpenAI and compatible services such as DeepSeek). +import { explicitEffort, fileKind, fileText, mediaUrl, messageParts, ModelRequestError, parseEvent, parseToolArguments, + postWithFallback, providerError, readSse, reasoningOrigin, reasoningProviderOptions, rejectedOption, streamToolCalls, textValue, toolSchema, + unsupportedFileNote, validFunctionName } from './model-common.mjs'; + +export const FORMAT = 'openai'; + +export function chatEndpoint(baseUrl) { + const url = new URL(baseUrl); + if (!['http:', 'https:'].includes(url.protocol)) throw new TypeError('baseUrl must use HTTP or HTTPS'); + url.pathname = url.pathname.replace(/\/+$/, ''); + if (!url.pathname.endsWith('/chat/completions')) url.pathname += '/chat/completions'; + return url.href; +} + +// Reasoning models of OpenAI take max_completion_tokens; most compatible servers take max_tokens. +const COMPLETION_TOKENS = /^(?:o\d|gpt-5|gpt-6|gpt-4\.1|codex)/i; +export function maxTokensParameter(model, dropped = new Set()) { + const preferred = COMPLETION_TOKENS.test(model) ? 'max_completion_tokens' : 'max_tokens'; + const other = preferred === 'max_tokens' ? 'max_completion_tokens' : 'max_tokens'; + return !dropped.has(preferred) ? preferred : !dropped.has(other) ? other : undefined; +} + +/** Chat reasoning parameters: reasoning_effort, plus DeepSeek's thinking switch. */ +export function chatReasoning(model, effort) { + const level = explicitEffort(effort); + if (!level) return {}; + return { reasoning_effort: level, ...(/deepseek/i.test(model) ? { thinking: { type: level === 'none' ? 'disabled' : 'enabled' } } : {}) }; +} + +function contentPart(part, role) { + if (part.type === 'text') return { type: 'text', text: part.text }; + if (part.type === 'image' && role === 'user') return { type: 'image_url', image_url: { url: mediaUrl(part) } }; + if (part.type === 'file' && role === 'user') { + const kind = fileKind(part); + if (kind === 'image') return { type: 'image_url', image_url: { url: mediaUrl(part, part.mimeType) } }; + if (kind === 'pdf') return { type: 'file', file: { filename: part.filename ?? 'document.pdf', file_data: mediaUrl(part, part.mimeType) } }; + if (kind === 'text') return { type: 'text', text: `${part.filename ? `${part.filename}:\n` : ''}${fileText(part)}` }; + return { type: 'text', text: unsupportedFileNote(part) }; + } + throw new TypeError(`Unsupported ${role} content type: ${part.type}`); +} + +/** + * Translate CoreMessages without losing screenshots. reasoning_content is replayed only for + * reasoning this format produced for the same model (DeepSeek needs it during tool use). + */ +export function convertChatMessages(messages, { model, providerId, replayReasoning = true } = {}) { + const output = []; + let toolImages = []; + const skippedToolCalls = new Set(); + const flushToolImages = () => { + if (!toolImages.length) return; + output.push({ role: 'user', content: [{ type: 'text', text: 'Screenshots from the preceding tool results:' }, ...toolImages] }); + toolImages = []; + }; + for (const message of messages) { + if (message.role !== 'tool') flushToolImages(); + const parts = messageParts(message); + if (message.role === 'tool') { + for (const part of parts) { + if (part.type !== 'tool-result' || !part.toolCallId) throw new TypeError('Tool messages require tool-result parts and toolCallId'); + if (skippedToolCalls.has(part.toolCallId)) continue; + const extra = part.experimental_content ?? []; + const fallback = extra.filter(p => p.type === 'text').map(p => p.text).join('\n'); + output.push({ role: 'tool', tool_call_id: part.toolCallId, content: part.result === undefined ? fallback : textValue(part.result) }); + toolImages.push(...extra.filter(p => p.type === 'image').map(p => ({ type: 'image_url', image_url: { url: mediaUrl(p) } }))); + } + } else if (message.role === 'assistant') { + const content = parts.filter(p => p.type === 'text').map(p => p.text).join(''); + const reasoning = replayReasoning ? parts.filter(p => { + if (p.type !== 'reasoning' || !p.text) return false; + const origin = reasoningOrigin(p); + // Legacy parts carry no origin; signed parts belong to another API format. + return origin.format ? origin.format === FORMAT && (!model || origin.model === model) && + (!origin.providerId || !providerId || origin.providerId === providerId) : !p.signature; + }).map(p => p.text).join('') : ''; + const calls = parts.filter(p => p.type === 'tool-call' && validFunctionName(p.toolName)).map(p => ({ + id: p.toolCallId, type: 'function', function: { name: p.toolName, arguments: textValue(p.args ?? {}) } })); + for (const part of parts) if (part.type === 'tool-call' && !validFunctionName(part.toolName) && part.toolCallId) skippedToolCalls.add(part.toolCallId); + output.push({ role: 'assistant', content: content || (calls.length ? null : ''), + ...(reasoning ? { reasoning_content: reasoning } : {}), ...(calls.length ? { tool_calls: calls } : {}) }); + } else if (['user', 'system', 'developer'].includes(message.role)) { + const content = parts.map(part => contentPart(part, message.role)); + output.push({ role: message.role, content: content.every(p => p.type === 'text') ? content.map(p => p.text).join('') : content }); + } else { + throw new TypeError(`Unsupported message role: ${message.role}`); + } + } + flushToolImages(); + return output; +} + +export function convertChatTools(tools = []) { + return tools.map(tool => { + const { name, description, parameters } = toolSchema(tool); + return { type: 'function', function: { name, description, parameters } }; + }); +} + +const OPTIONAL = ['stream_options', 'reasoning_effort', 'thinking', 'max_tokens', 'max_completion_tokens']; + +/** One streamed Chat Completions turn; yields Harness stream parts, returns the assembled message. */ +export async function* chatTurn(context) { + const { fetchImpl, endpoint, apiKey, headers, model, messages, tools, effort, maxTokens, requestOptions, signal, waitForIO, state, providerId, + notifyRequest, onModel, onId, onUsage } = context; + const functions = convertChatTools(tools); + const { http } = await postWithFallback({ fetchImpl, url: endpoint, apiKey, signal, waitForIO, state, optional: OPTIONAL, + fallbacks: [{ name: 'retry without replayed reasoning', applies: (error, body) => error.status === 400 && + body.messages.some(message => message.reasoning_content) && + (/(?:^|\.)reasoning_content$/.test(error.param ?? '') || rejectedOption(error, ['reasoning_content'])), + apply: () => { state.stripReasoning = true; } }], + headers: () => { + const value = new Headers(headers); + value.set('content-type', 'application/json'); + value.set('accept', 'text/event-stream'); + if (apiKey) value.set('authorization', `Bearer ${apiKey}`); + return value; + }, + build: () => { + const limit = maxTokens === undefined ? undefined : maxTokensParameter(model, state.dropped); + return { ...requestOptions, ...chatReasoning(model, effort), model, + messages: convertChatMessages(messages, { model, providerId, replayReasoning: !state.stripReasoning }), + stream: true, stream_options: { ...requestOptions?.stream_options, include_usage: true }, + ...(functions.length ? { tools: functions } : {}), ...(limit ? { [limit]: maxTokens } : {}) }; + } }); + notifyRequest(http.headers.get('x-request-id') ?? http.headers.get('request-id')); + let id, responseModel = model, text = '', reasoning = '', rawUsage = {}, finishReason, receivedChoice = false, receivedDone = false; + const toolCalls = new Map(), options = () => ({ providerOptions: reasoningProviderOptions({ format: FORMAT, model: responseModel, providerId }) }); + for await (const data of readSse(http.body, { waitForIO })) { + signal.throwIfAborted(); + if (data.trim() === '[DONE]') { receivedDone = true; break; } + const chunk = parseEvent(data); + if (chunk.error) throw providerError(chunk, undefined, http.headers, apiKey); + if (chunk.id) { id = chunk.id; onId(id); notifyRequest(id); } + if (chunk.model) { responseModel = chunk.model; onModel(responseModel); } + if (chunk.usage) { rawUsage = { ...rawUsage, ...chunk.usage }; onUsage(rawUsage); } + const choice = chunk.choices?.find(item => (item.index ?? 0) === 0); + if (!choice) continue; + receivedChoice = true; + if (choice.finish_reason) finishReason = choice.finish_reason; + const delta = choice.delta ?? {}; + // DeepSeek and Qwen use reasoning_content; OpenRouter and vLLM use reasoning. + const thought = typeof delta.reasoning_content === 'string' ? delta.reasoning_content : typeof delta.reasoning === 'string' ? delta.reasoning : ''; + if (thought) { reasoning += thought; yield { type: 'reasoning', textDelta: thought, ...options() }; } + for (const value of [delta.content, delta.refusal]) { + if (typeof value === 'string' && value) { text += value; yield { type: 'text-delta', textDelta: value }; } + } + for (const part of delta.tool_calls ?? []) { + const index = part.index ?? 0; + const call = toolCalls.get(index) ?? { id: '', name: '', arguments: '' }; + if (part.id) call.id += part.id; + if (part.function?.name) call.name += part.function.name; + if (part.function?.arguments) call.arguments += part.function.arguments; + toolCalls.set(index, call); + } + } + signal.throwIfAborted(); + if (finishReason === 'length' || finishReason === 'content_filter') { + throw new ModelRequestError(`Model response stopped with ${finishReason}`, { code: finishReason }); + } + // Compatible endpoints differ: some omit [DONE], some omit finish_reason, and some report "stop" + // after tool calls. Either marker completes the stream; the tool calls received are used as sent. + if (!receivedChoice || (!receivedDone && !finishReason)) throw new ModelRequestError('Model SSE stream ended before a completion marker'); + const content = []; + if (reasoning) content.push({ type: 'reasoning', text: reasoning, ...options() }); + if (text) content.push({ type: 'text', text }); + const calls = [...toolCalls.entries()].sort(([a], [b]) => a - b).map(([, call]) => { + if (!call.id || !validFunctionName(call.name)) throw new ModelRequestError('Model response included an invalid function name'); + return { type: 'tool-call', toolCallId: call.id, toolName: call.name, args: parseToolArguments(call.name, call.arguments, tools) }; + }); + yield* streamToolCalls(calls, messages, signal); + content.push(...calls); + return { id, model: responseModel, content, toolCalls: calls.length, usage: rawUsage }; +} diff --git a/host/runtime/openai-responses.mjs b/host/runtime/openai-responses.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d0183fb81a678c3ccacbf6fd95104c8bdf8ca494 --- /dev/null +++ b/host/runtime/openai-responses.mjs @@ -0,0 +1,350 @@ +// OpenAI Responses format (POST /v1/responses), used statelessly: store=false, with +// encrypted reasoning carried in the conversation instead of on the server. +import { createHash } from 'node:crypto'; +import { explicitEffort, fileKind, fileText, mediaUrl, messageParts, ModelRequestError, parseEvent, parseToolArguments, + postWithFallback, providerError, readSse, reasoningOrigin, reasoningProviderOptions, replayRejected, streamToolCalls, + textValue, toolSchema, unsupportedFileNote } from './model-common.mjs'; + +export const FORMAT = 'openai-responses'; + +// Keep replay within the Responses provider's observed function-name limit. +// Reject malformed model output before it reaches persisted conversation history. +const validFunctionName = value => typeof value === 'string' && value.length > 0 && value.length <= 128; + +export function responsesEndpoint(baseUrl) { + const url = new URL(baseUrl); + if (!['http:', 'https:'].includes(url.protocol)) throw new TypeError('baseUrl must use HTTP or HTTPS'); + url.pathname = url.pathname.replace(/\/+$/, ''); + if (!url.pathname.endsWith('/responses')) url.pathname += '/responses'; + return url.href; +} + +/** A model whose catalog lists only 'none' does not reason; unknown models are assumed to. */ +export function reasons(efforts) { + return !(Array.isArray(efforts) && efforts.length > 0 && efforts.every(level => level === 'none')); +} + +/** Request options: stateless storage, reasoning effort with summaries, encrypted reasoning. */ +export function responsesOptions(model, { effort, efforts, maxTokens } = {}) { + const level = explicitEffort(effort), thinking = reasons(efforts) && level !== 'none'; + const reasoning = reasons(efforts) ? { ...(level ? { effort: level } : {}), ...(thinking ? { summary: 'auto' } : {}) } : null; + return { store: false, parallel_tool_calls: true, + ...(reasoning && Object.keys(reasoning).length ? { reasoning } : {}), + ...(thinking ? { include: ['reasoning.encrypted_content'] } : {}), + ...(Number.isSafeInteger(maxTokens) && maxTokens > 0 ? { max_output_tokens: maxTokens } : {}) }; +} + +function userContent(part) { + if (part.type === 'text') return part.text ? { type: 'input_text', text: part.text } : null; + if (part.type === 'image') return { type: 'input_image', image_url: mediaUrl(part), detail: 'auto' }; + if (part.type === 'file') { + const kind = fileKind(part); + if (kind === 'image') return { type: 'input_image', image_url: mediaUrl(part, part.mimeType), detail: 'auto' }; + if (kind === 'pdf') { + const url = mediaUrl(part, part.mimeType); + return /^https?:/i.test(url) ? { type: 'input_file', file_url: url } : { type: 'input_file', filename: part.filename ?? 'document.pdf', file_data: url }; + } + if (kind === 'text') return { type: 'input_text', text: `${part.filename ? `${part.filename}:\n` : ''}${fileText(part)}` }; + return { type: 'input_text', text: unsupportedFileNote(part) }; + } + throw new TypeError(`Unsupported user content type: ${part.type}`); +} + +/** Encrypted reasoning is readable only by the model that produced it. */ +function replayableReasoning(part, model, providerId) { + const origin = reasoningOrigin(part); + if (origin.model !== model) return null; + if (origin.providerId && providerId && origin.providerId !== providerId) return null; + if (part.type === 'reasoning') { + if (!part.signature || !(origin.format === FORMAT || (!origin.format && origin.summarized))) return null; + return { type: 'reasoning', ...(origin.itemId ? { id: origin.itemId } : {}), + summary: part.text ? [{ type: 'summary_text', text: part.text }] : [], encrypted_content: part.signature }; + } + if (part.type === 'redacted-reasoning') { + // The original Harness turns summarized reasoning into redacted parts when it rebuilds a turn. + if (!part.data || (origin.format && origin.format !== FORMAT)) return null; + return { type: 'reasoning', ...(origin.itemId ? { id: origin.itemId } : {}), summary: [], encrypted_content: part.data }; + } + return null; +} + +/** CoreMessages to Responses input items and instructions. */ +export function convertResponsesInput(messages, { model, providerId, replayReasoning = true, inlineToolImages = true } = {}) { + const instructions = [], input = []; + let leading = true, pendingImages = []; + const skippedToolCalls = new Set(); + const flushImages = () => { + if (!pendingImages.length) return; + input.push({ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Screenshots from the preceding tool results:' }, ...pendingImages] }); + pendingImages = []; + }; + let replayed = 0; + for (const message of messages) { + const parts = messageParts(message); + if (message.role !== 'tool') flushImages(); + if (message.role === 'system' || message.role === 'developer') { + const text = parts.filter(part => part.type === 'text').map(part => part.text).join(''); + if (!text) continue; + if (leading) instructions.push(text); + else input.push({ type: 'message', role: 'developer', content: [{ type: 'input_text', text }] }); + continue; + } + leading = false; + if (message.role === 'user') { + const content = parts.map(userContent).filter(Boolean); + if (content.length) input.push({ type: 'message', role: 'user', content }); + } else if (message.role === 'assistant') { + const items = []; + for (const part of parts) { + if (part.type === 'reasoning' || part.type === 'redacted-reasoning') { + const item = replayReasoning ? replayableReasoning(part, model, providerId) : null; + if (item) { items.push(item); replayed++; } + } else if (part.type === 'text') { + if (!part.text) continue; + const phase = reasoningOrigin(part).phase; + const previous = items.at(-1); + if (previous?.type === 'message' && previous.phase === phase) previous.content += part.text; + else items.push({ type: 'message', role: 'assistant', content: part.text, ...(phase ? { phase } : {}) }); + } else if (part.type === 'tool-call') { + // Older Host versions could persist a malformed upstream function name. + // Omit it and its result instead of replaying an API-invalid call forever. + if (!validFunctionName(part.toolName)) { + if (typeof part.toolCallId === 'string') skippedToolCalls.add(part.toolCallId); + continue; + } + items.push({ type: 'function_call', call_id: part.toolCallId, name: part.toolName, arguments: textValue(part.args ?? {}) }); + } + } + // A reasoning item must be followed by the output it led to. + while (items.at(-1)?.type === 'reasoning') { items.pop(); replayed--; } + input.push(...items); + } else if (message.role === 'tool') { + for (const part of parts) { + if (part.type !== 'tool-result' || !part.toolCallId) throw new TypeError('Tool messages require tool-result parts and toolCallId'); + if (skippedToolCalls.has(part.toolCallId)) continue; + const extra = part.experimental_content ?? []; + const text = part.result === undefined ? extra.filter(item => item.type === 'text').map(item => item.text).join('\n') : textValue(part.result); + const images = extra.filter(item => item.type === 'image').map(item => ({ type: 'input_image', image_url: mediaUrl(item), detail: 'auto' })); + if (images.length && inlineToolImages) { + input.push({ type: 'function_call_output', call_id: part.toolCallId, output: [...(text ? [{ type: 'input_text', text }] : []), ...images] }); + } else { + input.push({ type: 'function_call_output', call_id: part.toolCallId, output: text || '(empty)' }); + pendingImages.push(...images); + } + } + } else { + throw new TypeError(`Unsupported message role: ${message.role}`); + } + } + flushImages(); + return { instructions: instructions.join('\n\n'), input, replayed }; +} + +export function convertResponsesTools(tools = []) { + return tools.map(tool => ({ type: 'function', ...toolSchema(tool), strict: false })); +} + +/** Normalize Responses usage to the OpenAI Chat fields recorded by the usage ledger. */ +export function responsesUsage(raw = {}) { + const count = value => Number.isFinite(value) && value >= 0 ? value : 0; + const input = count(raw.input_tokens), output = count(raw.output_tokens); + return { prompt_tokens: input, completion_tokens: output, total_tokens: count(raw.total_tokens ?? input + output), + prompt_tokens_details: { cached_tokens: count(raw.input_tokens_details?.cached_tokens) }, + cache_creation_input_tokens: count(raw.input_tokens_details?.cache_write_tokens), + completion_tokens_details: { reasoning_tokens: count(raw.output_tokens_details?.reasoning_tokens) } }; +} + +// Routes the same conversation to the same cache shard: model, instructions and the opening request. +function promptCacheKey(model, instructions, input) { + const first = input.find(item => item.type === 'message' && item.role === 'user'); + return createHash('sha256').update(JSON.stringify([model, instructions, first?.content ?? null])).digest('hex').slice(0, 48); +} + +const OPTIONAL = ['reasoning.summary', 'include', 'prompt_cache_key', 'parallel_tool_calls', 'store', 'reasoning.effort', 'max_output_tokens']; + +function incomplete(reason) { + if (reason === 'max_output_tokens') return new ModelRequestError('Model response stopped with max_output_tokens', { code: 'length' }); + if (reason === 'content_filter') return new ModelRequestError('Model response stopped with content_filter', { code: 'content_filter' }); + return new ModelRequestError(`Model response is incomplete${reason ? ` (${reason})` : ''}`, { code: reason }); +} + +/** One streamed Responses turn; yields Harness stream parts, returns the assembled message. */ +export async function* responsesTurn(context) { + const { fetchImpl, endpoint, apiKey, headers, model, messages, tools, effort, efforts, maxTokens, signal, waitForIO, state, + providerId, notifyRequest, onModel, onId, onUsage } = context; + const functions = convertResponsesTools(tools); + let replayed = 0, inlineImages = false; + const { http } = await postWithFallback({ fetchImpl, url: endpoint, apiKey, signal, waitForIO, state, optional: OPTIONAL, + headers: () => { + const value = new Headers(headers); + value.set('content-type', 'application/json'); + value.set('accept', 'text/event-stream'); + if (apiKey) value.set('authorization', `Bearer ${apiKey}`); + return value; + }, + fallbacks: [ + { name: 'retry without replayed reasoning', applies: error => replayed > 0 && replayRejected(error), apply: () => { state.stripReasoning = true; } }, + { name: 'tool screenshots as a message', applies: error => inlineImages && error.status === 400 && /function_call_output|input_image|output/i.test(error.message), + apply: () => { state.toolImagesAsMessage = true; } }, + ], + build: () => { + const converted = convertResponsesInput(messages, { model, providerId, replayReasoning: !state.stripReasoning, + inlineToolImages: !state.toolImagesAsMessage }); + replayed = converted.replayed; + inlineImages = converted.input.some(item => item.type === 'function_call_output' && Array.isArray(item.output)); + return { model, ...(converted.instructions ? { instructions: converted.instructions } : {}), input: converted.input, + ...(functions.length ? { tools: functions } : {}), stream: true, + ...responsesOptions(model, { effort, efforts, maxTokens }), + prompt_cache_key: promptCacheKey(model, converted.instructions, converted.input) }; + } }); + notifyRequest(http.headers.get('x-request-id') ?? http.headers.get('request-id')); + let id, responseModel = model, rawUsage = {}, finished = false; + const items = new Map(); + const item = (index, type, id) => { + if (!Number.isSafeInteger(index) || index < 0) throw new ModelRequestError('Invalid model output item index'); + if (!items.has(index)) items.set(index, { summary: [], reasoning: '', text: '', arguments: '', emitted: false }); + const entry = items.get(index); + if ((type && entry.type && type !== entry.type) || (id && entry.id && id !== entry.id)) { + throw new ModelRequestError('Conflicting model output item identity'); + } + entry.type ??= type; entry.id ??= id; + return entry; + }; + const reasoningOptions = (entry, summarized) => ({ + providerOptions: reasoningProviderOptions({ format: FORMAT, model: responseModel, providerId, summarized, itemId: entry.id }) }); + const start = response => { + if (id && response?.id && response.id !== id) throw new ModelRequestError('Conflicting model response ID'); + if (response?.id && response.id !== id) { id = response.id; onId(id); notifyRequest(id); } + if (response?.model) { responseModel = response.model; onModel(responseModel); } + }; + // Both output_item.done and response.completed.output can carry the same full item. + // Append only previously unseen text; never replace a streamed identity or replay a signature. + function* finishItem(index, snapshot) { + if (!snapshot?.type) throw new ModelRequestError('Missing model output item'); + const entry = item(index, snapshot.type, snapshot.id); + if (snapshot.status && snapshot.status !== 'completed') throw new ModelRequestError(`Model output item is ${snapshot.status}`); + if (entry.type === 'message') { + entry.phase = snapshot.phase ?? entry.phase; + if (!Array.isArray(snapshot.content)) return; + const text = snapshot.content.map(part => part.text ?? part.refusal ?? '').join(''); + if (!text.startsWith(entry.text)) throw new ModelRequestError('Conflicting model output text'); + const suffix = text.slice(entry.text.length); + entry.text = text; + if (suffix) yield { type: 'text-delta', textDelta: suffix }; + } else if (entry.type === 'function_call') { + if ((entry.name && snapshot.name && entry.name !== snapshot.name) || + (entry.callId && snapshot.call_id && entry.callId !== snapshot.call_id)) throw new ModelRequestError('Conflicting model tool call identity'); + entry.name ??= snapshot.name; entry.callId ??= snapshot.call_id; + if (typeof snapshot.arguments === 'string') { + if (!snapshot.arguments.startsWith(entry.arguments)) throw new ModelRequestError('Conflicting model tool arguments'); + entry.arguments = snapshot.arguments; + } + } else if (entry.type === 'reasoning') { + const priorSummary = entry.summary.filter(Boolean).join('\n\n'), prior = priorSummary || entry.reasoning; + if (snapshot.summary?.length) entry.summary = snapshot.summary.map(part => part.text ?? ''); + if (snapshot.content?.length) entry.reasoning = snapshot.content.map(part => part.text ?? '').join(''); + const summary = entry.summary.filter(Boolean).join('\n\n'), text = summary || entry.reasoning; + if (!text.startsWith(prior)) throw new ModelRequestError('Conflicting model reasoning text'); + if (text.length > prior.length) { + entry.emitted = true; + yield { type: 'reasoning', textDelta: text.slice(prior.length), ...reasoningOptions(entry, Boolean(summary)) }; + } + if (snapshot.encrypted_content && snapshot.encrypted_content !== entry.encrypted) { + if (entry.encrypted) throw new ModelRequestError('Conflicting model reasoning signature'); + entry.encrypted = snapshot.encrypted_content; + if (entry.emitted) yield { type: 'reasoning-signature', signature: entry.encrypted }; + else yield { type: 'redacted-reasoning', data: entry.encrypted, ...reasoningOptions(entry, true) }; + } + } + } + for await (const data of readSse(http.body, { waitForIO })) { + signal.throwIfAborted(); + if (data.trim() === '[DONE]') break; + const event = parseEvent(data); + switch (event.type) { + case 'response.created': case 'response.in_progress': case 'response.queued': + start(event.response); break; + case 'response.output_item.added': { + const entry = item(event.output_index, event.item?.type, event.item?.id); + if (entry.added) throw new ModelRequestError('Duplicate model output item'); + Object.assign(entry, { added: true, name: event.item?.name, callId: event.item?.call_id, phase: event.item?.phase }); + if (event.item?.arguments) entry.arguments = event.item.arguments; + break; + } + case 'response.reasoning_summary_text.delta': case 'response.reasoning_text.delta': { + if (!event.delta) break; + const entry = item(event.output_index, 'reasoning', event.item_id), summarized = event.type === 'response.reasoning_summary_text.delta'; + let delta = event.delta; + if (summarized) { + const index = event.summary_index ?? 0; + if (entry.summary[index] === undefined && entry.summary.length) delta = `\n\n${delta}`; + entry.summary[index] = (entry.summary[index] ?? '') + event.delta; + } else entry.reasoning += event.delta; + entry.emitted = true; + yield { type: 'reasoning', textDelta: delta, ...reasoningOptions(entry, summarized) }; + break; + } + case 'response.output_text.delta': case 'response.refusal.delta': { + if (!event.delta) break; + const entry = item(event.output_index, 'message', event.item_id); + entry.text += event.delta; + yield { type: 'text-delta', textDelta: event.delta }; + break; + } + case 'response.function_call_arguments.delta': + item(event.output_index, 'function_call', event.item_id).arguments += event.delta ?? ''; + break; + case 'response.function_call_arguments.done': + yield* finishItem(event.output_index, { type: 'function_call', id: event.item_id, name: event.name, arguments: event.arguments }); + break; + case 'response.output_item.done': + yield* finishItem(event.output_index, event.item); + break; + case 'response.completed': case 'response.incomplete': case 'response.failed': case 'response.cancelled': { + const response = event.response; + if (!response) throw new ModelRequestError('Missing terminal model response'); + start(response); + if (response.usage) { rawUsage = response.usage; onUsage(responsesUsage(rawUsage)); } + if (event.type === 'response.failed' || response.error || response.status === 'failed') { + throw providerError({ error: response.error ?? { message: 'Model response failed' } }, undefined, http.headers, apiKey); + } + if (event.type === 'response.incomplete' || response.status === 'incomplete' || response.incomplete_details) throw incomplete(response.incomplete_details?.reason); + if (event.type !== 'response.completed' || (response.status && response.status !== 'completed')) throw incomplete(response.status ?? event.type); + if (response.output !== undefined) { + if (!Array.isArray(response.output) || [...items.keys()].some(index => index >= response.output.length)) { + throw new ModelRequestError('Model output snapshot is missing a streamed item'); + } + for (const [index, output] of response.output.entries()) yield* finishItem(index, output); + } + finished = true; + break; + } + case 'error': + throw providerError(event.error ? event : { error: event }, undefined, http.headers, apiKey); + default: + break; + } + if (finished) break; + } + signal.throwIfAborted(); + if (!finished) throw new ModelRequestError('Model SSE stream ended before a completion marker'); + const content = [], calls = []; + for (const [, entry] of [...items.entries()].sort(([a], [b]) => a - b)) { + if (entry.type === 'reasoning') { + const summary = entry.summary.filter(Boolean).join('\n\n'), text = summary || entry.reasoning; + if (!text && !entry.encrypted) continue; + if (!text) { content.push({ type: 'redacted-reasoning', data: entry.encrypted, ...reasoningOptions(entry, true) }); continue; } + content.push({ type: 'reasoning', text, ...(entry.encrypted ? { signature: entry.encrypted } : {}), + ...reasoningOptions(entry, Boolean(summary) || !entry.reasoning) }); + } else if (entry.type === 'message') { + if (entry.text) content.push({ type: 'text', text: entry.text, ...(entry.phase ? { providerOptions: { grokbot: { phase: entry.phase } } } : {}) }); + } else if (entry.type === 'function_call') { + if (!entry.callId || !validFunctionName(entry.name)) throw new ModelRequestError('Model response included an invalid function name'); + const call = { type: 'tool-call', toolCallId: entry.callId, toolName: entry.name, args: parseToolArguments(entry.name, entry.arguments, tools) }; + // Output order is kept: each reasoning item must precede the output it led to on replay. + calls.push(call); content.push(call); + } + } + yield* streamToolCalls(calls, messages, signal); + return { id, model: responseModel, content, toolCalls: calls.length, usage: responsesUsage(rawUsage) }; +} diff --git a/host/runtime/prompt-runtime.mjs b/host/runtime/prompt-runtime.mjs index 41bc89df045b79cdea0c434dbed4d53b26302428..a42719e539c4848a6444e38dd9d8337f17566b99 100644 --- a/host/runtime/prompt-runtime.mjs +++ b/host/runtime/prompt-runtime.mjs @@ -2,8 +2,21 @@ import { join } from 'node:path'; import { readJson, writePrivate } from '../server/storage.mjs'; import { promptDigest, promptId, promptRoles, validatePrompt } from '../server/prompt-settings.mjs'; +function memoryAccessDirective(memoryRoot) { + const root = memoryRoot.replace(/\/+$/, '') || '/'; + return [ + `Memory access is configured for this turn: agent memory is mounted at ${root}/agents and shared user memory at ${root}/user-memory.`, + 'Use memory proactively whenever it can affect the answer, without waiting for the user to ask. The normal Memory sections may already include profile and recent facts; when you need older or omitted facts, inspect the corresponding files with Read or Shell on your own computer.', + 'Do not repeat an earlier turn\'s "not mounted" or "not readable" result without rechecking in the current turn.', + 'A missing monthly log means that no file has been recorded for that month yet, not that the entire memory volume is unavailable.', + ].join(' '); +} + /** Only base instructions are catalogued. Profile, memory, skills and user content stay in the original assembler. */ -export async function installLocalPromptPolicy(directory, library, { pollMs = 1000 } = {}) { +export async function installLocalPromptPolicy(directory, library, { + pollMs = 1000, revision = 'local', memoryRoot = process.env.SAND_DATA_ROOT ?? '/data/runtime/host-data', + memoryMounts = process.env.GROKBOT_HOST_MEMORY_MOUNTS === '1', +} = {}) { const settingsPath = join(directory, 'prompt-settings.json'), catalogPath = join(directory, 'prompt-catalog.json'); let settings = { version: 1, entries: {} }, catalog = await readJson(catalogPath, { version: 1, entries: [] }), tail = Promise.resolve(), reading = false; let stopped = false; @@ -21,7 +34,7 @@ export async function installLocalPromptPolicy(directory, library, { pollMs = 10 return id; } catalog.entries.push({ id, role, original, digest: promptDigest(original), observedAt: Date.now(), observed, - source: 'd0a4baa · system-prompt-assembly' }); + source: `${revision} · system-prompt-assembly` }); catalog.entries = catalog.entries.slice(-100); void flush(); return id; } async function refresh() { @@ -54,8 +67,16 @@ export async function installLocalPromptPolicy(directory, library, { pollMs = 10 const render = (role, original) => { id = observe(role, original); if (!id) return original; const selected = frozen[id]?.revisions?.at(-1)?.content; - if (selected === undefined) return original; - try { return validatePrompt(selected); } catch { return original; } + let rendered = original; + if (selected !== undefined) { + try { rendered = validatePrompt(selected); } catch { rendered = original; } + } + if (role !== 'parent' || !memoryMounts) return rendered; + try { + return validatePrompt(`${rendered.trimEnd()}\n\n${memoryAccessDirective(memoryRoot)}`); + } catch { + return rendered; + } }; render.recordAssembly = value => { assembly = value; publish(); }; render.recordTools = values => { diff --git a/host/runtime/recovered-blob-worker.mjs b/host/runtime/recovered-blob-worker.mjs index 0c682b9edd2f4adcc4f66beb2cb071a6deba22ee..1b47671a61c39de0049e3dc58a6a23b78ce40cec 100644 --- a/host/runtime/recovered-blob-worker.mjs +++ b/host/runtime/recovered-blob-worker.mjs @@ -4,8 +4,9 @@ import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { isMainThread, threadId } from 'node:worker_threads'; import { constructRecoveredModules } from './recovered-modules.mjs'; +import inputs from '../recipes/host/manifest.json' with { type: 'json' }; -const sourceSha256 = '868572888c71b317c7878b5efc81b029aa99192e3bef7402591759388a6bcf3c'; +const sourceSha256 = inputs.sourceSha256['agent-isolation/agent-store-worker.cjs']; const hash = bytes => createHash('sha256').update(bytes).digest('hex'); export async function describeRecoveredBlobWorker(state) { diff --git a/host/runtime/recovered-host-core.mjs b/host/runtime/recovered-host-core.mjs index a29801c9bd76fabbac2ed35a69862e57f650ccf0..a3e94fd5ae93c91e5dd277db07fba615c2006707 100644 --- a/host/runtime/recovered-host-core.mjs +++ b/host/runtime/recovered-host-core.mjs @@ -12,13 +12,14 @@ import { installRecoveredStorage } from './recovered-storage.mjs'; import { installRecoveredPromptTools } from './recovered-prompt-tools.mjs'; import { installRecoveredHostKernel } from './recovered-host-kernel.mjs'; import { installRecoveredToolFramework } from './recovered-tool-framework.mjs'; +import inputs from '../recipes/host/manifest.json' with { type: 'json' }; /** Install editable recovery modules before any Host service is constructed. */ export async function loadRecoveredHostCore(library, directory) { const modules = []; for (const filename of ['provenance.json', 'acceptance-provenance.json', 'handoff-provenance.json', 'host-flow-provenance.json', 'storage-provenance.json', 'worker-pool-provenance.json', 'tool-framework-provenance.json', 'engine-provenance.json', 'computer-provenance.json', 'prompt-tools-provenance.json', 'harness-provenance.json', 'host-execution-provenance.json', 'host-session-provenance.json', 'host-kernel-provenance.json']) { const manifest = JSON.parse(await readFile(join(directory, filename), 'utf8')); - if (manifest.sourceSha256 !== 'd7ffb02b831337f6e4618a2604fb6ecd00a7f75f4c4bf96f5075f54d473b7f67') { + if (manifest.sourceSha256 !== inputs.sourceSha256['host-main.cjs']) { throw new Error(`Unexpected recovered source: ${filename}`); } for (const entry of manifest.modules) { diff --git a/host/runtime/recovered-host-flow.mjs b/host/runtime/recovered-host-flow.mjs index 7ccaeec840e772d5550f923d7c29ce8a925fb786..0a676948b6637a6ed2161279ef9ea1da4c0a72e3 100644 --- a/host/runtime/recovered-host-flow.mjs +++ b/host/runtime/recovered-host-flow.mjs @@ -1,7 +1,35 @@ import { constructRecoveredModules } from './recovered-modules.mjs'; +const memoryFailureTags = new Set(['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'ETIMEDOUT', + 'UND_ERR_SOCKET', 'UND_ERR_CONNECT_TIMEOUT', 'AbortError', 'TimeoutError']); + +function reportMemoryFailure(error) { + const tag = [error?.code, error?.cause?.code, error?.name].find(value => memoryFailureTags.has(value)); + console.warn(`[memory] Post-turn memory model request failed (${tag ?? 'model error'})`); +} + +function memoryExecutor(executor) { + return { + appendMessages(messages) { executor.appendMessages(messages); return this; }, + stream(...args) { + const result = executor.stream(...args); + // The memory collector catches fullStream failures but never reads the new + // completion promises created by the Host's usage middleware above the adapter. + void Promise.all([result.response, result.usage, result.extendedUsage]).catch(reportMemoryFailure); + return result; + }, + }; +} + export function constructRecoveredHostFlow(library, directory) { - return constructRecoveredModules(library.hostFlowRecoveryPlan, library.getHostFlowRecoveryBindings(), directory, 'Host flow'); + const original = library.getHostFlowRecoveryBindings(); + if (typeof original.runTurnMemory !== 'function') throw new TypeError('Missing Host flow dependency: runTurnMemory'); + return constructRecoveredModules(library.hostFlowRecoveryPlan, { ...original, + runTurnMemory(store, progress, session, ...turnArgs) { + const memorySession = { getExecutor: (...args) => memoryExecutor(session.getExecutor(...args)) }; + return original.runTurnMemory(store, progress, memorySession, ...turnArgs); + }, + }, directory, 'Host flow'); } export async function installRecoveredHostFlow(library, directory) { diff --git a/host/runtime/reliability/tool-journal.mjs b/host/runtime/reliability/tool-journal.mjs index ade992ed750d0bba41a300edda6a0d2786611eba..11a0d1aaa621f09f7026ed9154b9e401b2bf0602 100644 --- a/host/runtime/reliability/tool-journal.mjs +++ b/host/runtime/reliability/tool-journal.mjs @@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'node:crypto'; import { mkdir, open, readFile, readdir, rename, rm, unlink } from 'node:fs/promises'; import { join, resolve } from 'node:path'; import { deserialize, serialize } from 'node:v8'; +import { awaitToolCallTurn } from './tool-order.mjs'; const scopes = new AsyncLocalStorage(); const executions = new AsyncLocalStorage(); @@ -90,6 +91,16 @@ export async function runJournaledTool({ descriptor, argumentsText, turnId = 'un const root = process.env.SAND_DATA_ROOT; if (!root) throw new Error('Tool execution requires SAND_DATA_ROOT for its durable journal'); if (typeof descriptor.toolCallId !== 'string' || !descriptor.toolCallId) throw new Error('Tool call ID is required'); + // Messages of one response run one after another in written order; other tools are not delayed. + const release = await awaitToolCallTurn(descriptor.toolCallId, signal); + try { return await runAdmitted({ descriptor, argumentsText, turnId, signal, isDeferred, execute, captureDelivery, onReplay, root }); } + finally { release(); } +} + +async function runAdmitted({ descriptor, argumentsText, turnId, signal, isDeferred, execute, captureDelivery, onReplay, root }) { + const scope = scopes.getStore(); + // The turn may have been cancelled while this message waited for an earlier one. + if (signal?.aborted) throw Object.assign(new Error('Tool execution aborted before admission'), { name: 'AbortError' }); let argumentsValue; try { argumentsValue = canonical(JSON.parse(argumentsText)); } catch { argumentsValue = argumentsText; } const fingerprint = digest(JSON.stringify({ name: descriptor.effectiveNativeToolCall?.toolName ?? descriptor.toolName, diff --git a/host/runtime/reliability/tool-order.mjs b/host/runtime/reliability/tool-order.mjs new file mode 100644 index 0000000000000000000000000000000000000000..aaa1d13aabd79aec61140879b5c26fa132e4a4cd --- /dev/null +++ b/host/runtime/reliability/tool-order.mjs @@ -0,0 +1,87 @@ +// Messages from one model response must reach the user in the order the model wrote them. +// The model layer hands the Harness a response's tool calls together, and the Harness then +// runs them concurrently (each first awaits its own durable journal admission), so without +// this the shortest message tends to arrive first. Other tools keep running in parallel. + +const ORDERED_TOOLS = new Set(['SendToUser', 'SendToAgent']); +// A predecessor that never executes (for example, rejected arguments) must not block forever. +const MAX_WAIT_MS = 15_000; +const STALE_MS = 10 * 60_000; +const calls = new Map(); +// Some providers number call IDs per response, so concurrent conversations can reuse an ID. Such +// calls run unordered (as without this module) instead of failing the turn or waiting on each other. +// The colliding calls finish well within a minute; after that the ID is ordered normally again. +const SHARED_MS = 60_000; +const shared = new Map(); +let sweepTimer; + +function release(id, entry) { + entry.resolve(); + if (calls.get(id) === entry) calls.delete(id); + if (!calls.size) { clearTimeout(sweepTimer); sweepTimer = undefined; } +} + +// One unreferenced timer for the whole map, including when the last turn is abandoned. +function scheduleSweep() { + if (sweepTimer || !calls.size) return; + const first = calls.values().next().value; + sweepTimer = setTimeout(() => { + sweepTimer = undefined; + const now = Date.now(); + for (const [id, entry] of calls) { + if (entry.createdAt + STALE_MS > now) break; + release(id, entry); + } + scheduleSweep(); + }, Math.max(1, first.createdAt + STALE_MS - Date.now())); + sweepTimer.unref?.(); +} + +/** Called by the model layer with one response's tool calls in written order. */ +export function recordToolCallOrder(list) { + const now = Date.now(); + for (const [id, until] of shared) if (until <= now) shared.delete(id); + const registered = new Map(); + const ordered = list.filter(({ toolCallId, toolName }) => ORDERED_TOOLS.has(toolName) && typeof toolCallId === 'string' && toolCallId); + const ids = new Set(); + for (const { toolCallId } of ordered) { + if (ids.has(toolCallId)) throw new Error('Ordered tool call ID is repeated in one response'); + ids.add(toolCallId); + } + let previous; + for (const { toolCallId } of ordered) { + const existing = calls.get(toolCallId); + if (existing || shared.has(toolCallId)) { + // Neither response may take over or wait on the other's entry for an ambiguous ID. + if (existing) release(toolCallId, existing); + shared.set(toolCallId, now + SHARED_MS); + continue; + } + let resolve; + const done = new Promise(settle => { resolve = settle; }); + const entry = { previous, done, resolve, createdAt: now }; + calls.set(toolCallId, entry); + registered.set(toolCallId, entry); + previous = done; + } + scheduleSweep(); + return id => { const entry = registered.get(id); if (entry) release(id, entry); }; +} + +/** Wait for the previous ordered call of the same response; the returned function marks this call finished. */ +export function awaitToolCallTurn(toolCallId, signal, { maxWaitMs = MAX_WAIT_MS } = {}) { + const entry = calls.get(toolCallId); + if (!entry) return Promise.resolve(() => {}); + return (async () => { + const previous = entry.previous; + if (previous && !signal?.aborted) { + let timer, onAbort; + await Promise.race([previous, + new Promise(settle => { timer = setTimeout(settle, maxWaitMs); }), + new Promise(settle => { onAbort = settle; signal?.addEventListener('abort', settle, { once: true }); })]); + clearTimeout(timer); + signal?.removeEventListener('abort', onAbort); + } + return () => release(toolCallId, entry); + })(); +} diff --git a/host/runtime/routing-log.mjs b/host/runtime/routing-log.mjs index ca66241f8e39ffe6e85d1a3fb57ab45b22b02582..c05d7e0c5b959fff305d75ee65a4ef5141b1d1c1 100644 --- a/host/runtime/routing-log.mjs +++ b/host/runtime/routing-log.mjs @@ -5,11 +5,30 @@ export function taskPreview(state) { return String(state.at(-1)?.text ?? '').replace(/(?:apikey_|sk-)[A-Za-z0-9_-]{16,}/g, '[redacted]') .replace(/Bearer\s+[A-Za-z0-9._-]+/gi, 'Bearer [redacted]').replace(/\s+/g, ' ').trim().slice(0, 240); } +function routingTarget(value) { + if (!value) return undefined; + return { + profileId: value.profileId, + profileName: value.profileName, + providerId: value.providerId, + providerName: value.providerName, + apiFormat: value.apiFormat, + model: value.model, + }; +} +function routingRecord(entry) { + const clean = { ...entry }; + if (clean.from) clean.from = routingTarget(clean.from); + if (clean.to) clean.to = routingTarget(clean.to); + if (Array.isArray(clean.skipped)) clean.skipped = clean.skipped.map(routingTarget).filter(Boolean); + return clean; +} export async function recordRouting(directory, entry) { if (!directory) return; const at = new Date().toISOString(); await mkdir(directory, { recursive: true, mode: 0o700 }); - await appendFile(join(directory, `${at.slice(0, 10)}.jsonl`), JSON.stringify({ id: randomUUID(), at, ...entry }) + '\n', { mode: 0o600 }); + await appendFile(join(directory, `${at.slice(0, 10)}.jsonl`), JSON.stringify({ id: randomUUID(), at, + ...routingRecord(entry) }) + '\n', { mode: 0o600 }); const files = (await readdir(directory)).filter(name => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(name)).sort(); for (const name of files.slice(0, -30)) await unlink(join(directory, name)).catch(() => {}); } diff --git a/host/runtime/usage-ledger.mjs b/host/runtime/usage-ledger.mjs index 7878df595a48c915b6677ffad0fad0eaaf10d80f..325475dae685b459ac322f65f6d48182e463e3d4 100644 --- a/host/runtime/usage-ledger.mjs +++ b/host/runtime/usage-ledger.mjs @@ -10,10 +10,11 @@ export function usageCounts(raw = {}) { cached: count(raw.prompt_cache_hit_tokens ?? raw.prompt_tokens_details?.cached_tokens), reasoning: count(raw.completion_tokens_details?.reasoning_tokens) }; } -export async function recordUsage(directory, { raw, model, kind = 'chat', effort, requestId, at = new Date() }) { +export async function recordUsage(directory, { raw, model, kind = 'chat', effort, requestId, profileId, providerId, at = new Date() }) { if (!directory || !raw || !Object.keys(raw).length) return; const timestamp = at.toISOString(); - const entry = { id: randomUUID(), at: timestamp, model, kind, effort, requestId, ...usageCounts(raw) }; + const entry = { id: randomUUID(), at: timestamp, model, kind, effort, requestId, + ...(profileId ? { profileId } : {}), ...(providerId ? { providerId } : {}), ...usageCounts(raw) }; await mkdir(directory, { recursive: true, mode: 0o700 }); // Each process appends one short JSON line; no read/modify/write race with the admin server. await appendFile(join(directory, timestamp.slice(0, 10) + '.jsonl'), JSON.stringify(entry) + '\n', { mode: 0o600 }); diff --git a/host/runtime/web-services.mjs b/host/runtime/web-services.mjs index f1e87c789907586804aae76a78311d0fc790a91d..b8909fe31d2c3e6f2ef4f3ead9cc6e87a7364d17 100644 --- a/host/runtime/web-services.mjs +++ b/host/runtime/web-services.mjs @@ -28,17 +28,33 @@ async function nativeResponse(provider, query, signal) { const citations = content.flatMap(item => item.annotations || []).filter(item => item.type === 'url_citation'); return { answer, documents: documents(citations.map(item => ({ title: item.title || item.url, url: item.url, text: '' }))) }; } +// Models with thinking always on reject a forced tool choice; they still call the tool when the prompt names it. +const automaticToolChoice = new Set(); async function nativeAnthropic(provider, kind, value, signal) { const type = kind === 'search' ? 'web_search_20250305' : 'web_fetch_20250910', name = kind === 'search' ? 'web_search' : 'web_fetch'; - const response = await fetch(`${provider.baseUrl}/messages`, { method: 'POST', redirect: 'error', signal, + const key = `${provider.baseUrl}\n${provider.model}`; + const send = toolChoice => fetch(`${provider.baseUrl}/messages`, { method: 'POST', redirect: 'error', signal, headers: { 'content-type': 'application/json', 'x-api-key': provider.apiKey, 'anthropic-version': '2023-06-01' }, body: JSON.stringify({ model: provider.model, max_tokens: 8000, tools: [{ type, name, max_uses: 1 }], - tool_choice: { type: 'tool', name }, messages: [{ role: 'user', content: kind === 'search' - ? `Search this query and return source-grounded findings: ${value}` : `Fetch this page and return its content: ${value}` }] }) }); + tool_choice: toolChoice, messages: [{ role: 'user', content: kind === 'search' + ? `Use the ${name} tool to search this query and return source-grounded findings: ${value}` + : `Use the ${name} tool to fetch this page and return its content: ${value}` }] }) }); + // Decide on what this request sent: a concurrent call may record the fallback while this one is in flight. + const forced = !automaticToolChoice.has(key); + let response = await send(forced ? { type: 'tool', name } : { type: 'auto' }); + if (response.status === 400 && forced) { + const detail = (await boundedBody(response, 64 * 1024).catch(() => Buffer.alloc(0))).toString('utf8'); + check(/tool[_ ]choice|forced tool/i.test(detail), 502, 'Service returned HTTP 400'); + automaticToolChoice.add(key); + console.warn(`[web] ${provider.model} rejects a forced tool choice; using automatic tool choice`); + response = await send({ type: 'auto' }); + } if (!response.ok) { await response.body?.cancel(); check(false, 502, `Service returned HTTP ${response.status}`); } let result; try { result = JSON.parse((await boundedBody(response)).toString('utf8')); } catch { check(false, 502, 'Invalid native web response'); } - const toolResults = result.content?.filter(item => item.type === `${name}_tool_result`) ?? []; - check(toolResults.length > 0 && !toolResults.some(item => item.content?.type?.endsWith('_error')), 502, `Native web ${kind} failed`); + // Parallel calls beyond max_uses come back as max_uses_exceeded errors; use whichever calls succeeded. + const toolResults = (result.content?.filter(item => item.type === `${name}_tool_result`) ?? []) + .filter(item => !item.content?.type?.endsWith('_error')); + check(toolResults.length > 0, 502, `Native web ${kind} failed`); if (kind === 'search') { const refs = toolResults.flatMap(item => Array.isArray(item.content) ? item.content : []); return { answer: result.content.filter(item => item.type === 'text').map(item => item.text).join('\n'), diff --git a/host/server/auth.mjs b/host/server/auth.mjs index 37f5bdd9d3391dfbc0229de3e1f629691e93714b..8b88d99ad1fe56803799ace3fbd57ff806d24964 100644 --- a/host/server/auth.mjs +++ b/host/server/auth.mjs @@ -21,6 +21,12 @@ const publicDevice = ({ }) => ({ id, name, platform, createdAt, revokedAt, lastSeenAt }); const normalizeKey = (value) => typeof value === "string" ? value.replace(/[\s-]/g, "").toUpperCase() : ""; +const validDeviceName = (value) => + check( + typeof value === "string" && value.trim().length > 0 && value.length <= 80, + 400, + "设备名称需要 1–80 个字符", + ); export class Auth { constructor( dataDir, @@ -29,6 +35,7 @@ export class Auth { this.dataDir = dataDir; this.sessionMs = sessionMs; this.pairingMs = pairingMs; + this.touchWrites = new Map(); this.store = new JsonStore(join(dataDir, "auth.json"), { version: 1, admin: null, @@ -93,12 +100,9 @@ export class Auth { return token; } adminSession(token) { - return ( - typeof token === "string" && - this.store.value.sessions.some( - (item) => item.hash === hash(token) && item.expiresAt > Date.now(), - ) - ); + if (typeof token !== "string") return false; + const fingerprint = hash(token), now = Date.now(); + return this.store.value.sessions.some(item => item.hash === fingerprint && item.expiresAt > now); } async logout(token) { await this.store.mutate((state) => { @@ -131,34 +135,44 @@ export class Auth { .filter((item) => item.expiresAt > Date.now()) .map(({ id, expiresAt }) => ({ id, expiresAt })); } - async pair({ pairingKey, deviceName, platform }) { - check( - typeof deviceName === "string" && - deviceName.trim().length > 0 && - deviceName.length <= 80, - 400, - "设备名称需要 1–80 个字符", - ); - check( + /** + * Pairs a client with a one-time code. `web` is set only by the Host's own web client sign-in; + * clients pairing through /connect/pair are desktops, Android phones or iOS devices. + */ + async pair({ pairingKey, deviceName, platform, clientKind }, { web = false } = {}) { + validDeviceName(deviceName); + if (!web) check( ["desktop", "ios"].includes(platform), 400, "设备类型应为 desktop 或 ios", ); - const token = secret(); - const id = randomUUID(); - await this.store.mutate((state) => { + const kind = web ? "web" : platform === "desktop" && clientKind === "android" ? "android" : platform; + return this.addDevice(deviceName, kind, state => { const index = state.pairing.findIndex( (item) => item.hash === hash(normalizeKey(pairingKey)) && item.expiresAt > Date.now(), ); check(index >= 0, 401, "配对码无效、已使用或已过期"); + return () => state.pairing.splice(index, 1); + }); + } + /** A browser opened from the signed-in admin page; the administrator needs no pairing code. */ + async addWebDevice(deviceName) { + return this.addDevice(deviceName, "web", () => () => {}); + } + async addDevice(deviceName, platform, authorize) { + validDeviceName(deviceName); + const token = secret(); + const id = randomUUID(); + await this.store.mutate((state) => { + const consume = authorize(state); check( state.devices.filter((item) => !item.revokedAt).length < 100, 409, "设备数量已达上限,请先撤销不用的设备", ); - state.pairing.splice(index, 1); + consume(); state.devices.push({ id, name: deviceName.trim(), @@ -173,8 +187,9 @@ export class Auth { } authenticate(token) { if (typeof token !== "string") return null; + const fingerprint = hash(token); const device = this.store.value.devices.find( - (item) => !item.revokedAt && item.hash === hash(token), + (item) => !item.revokedAt && item.hash === fingerprint, ); return device ? publicDevice(device) : null; } @@ -190,12 +205,17 @@ export class Auth { const device = this.device(id); if (!device || Date.now() - Date.parse(device.lastSeenAt ?? 0) < 60_000) return; - await this.store.mutate((state) => { + // One page load can request many resources before the first fsync has finished. + const inflight = this.touchWrites.get(id); + if (inflight) return inflight; + const pending = this.store.mutate((state) => { const current = state.devices.find( (item) => item.id === id && !item.revokedAt, ); if (current) current.lastSeenAt = new Date().toISOString(); }); + this.touchWrites.set(id, pending); + try { await pending; } finally { this.touchWrites.delete(id); } } async revoke(id) { await this.store.mutate((state) => { diff --git a/host/server/desktop-capabilities.mjs b/host/server/desktop-capabilities.mjs index 33749a2b8017ef42876923733c8d51a6a27705a2..f18b47ca30a45e5ff63fe1e0199a36710d82e382 100644 --- a/host/server/desktop-capabilities.mjs +++ b/host/server/desktop-capabilities.mjs @@ -6,6 +6,8 @@ const internalPrefix = '/internal/desktop-capabilities'; const object = value => value && typeof value === 'object' && !Array.isArray(value); const validId = value => typeof value === 'string' && value.length > 0 && value.length <= 160; const maxResultBytes = 24 * 1024 * 1024; +// Paired desktop clients announce their OS; machine IDs keep the original mac- form on macOS. +const desktopPlatforms = { darwin: 'mac', win32: 'win' }; const computerTool = /^(computer_(screenshot|click|move|drag|type|key|scroll|wait|check_permissions|apps|resolve_app|app_state|set_value|app_action)|codex_(start|status|continue|cancel|list))$/; /** Outbound device channels. A request is never retried after its provider leaves. */ @@ -24,7 +26,7 @@ export class DesktopCapabilities { list() { if (!this.enabled()) return []; return [...this.providers.values()].filter(p => p.tools && Date.now() - p.lastSeen <= 35000) - .map(p => ({ machineId: p.machineId, label: p.label, tools: p.tools })); + .map(p => ({ machineId: p.machineId, label: p.label, platform: p.platform, tools: p.tools })); } send(provider, value) { check(!provider.response.destroyed, 409, 'Computer disconnected'); @@ -37,7 +39,7 @@ export class DesktopCapabilities { error ? pending.reject(error) : pending.resolve(result); } async call(args, signal) { - check(this.enabled(), 409, 'Mac computer control is disabled'); + check(this.enabled(), 409, 'Computer control is disabled'); check(object(args) && validId(args.machineId) && validId(args.conversationId) && computerTool.test(args.toolId), 400, 'Invalid computer call'); check(object(args.arguments ?? {}) && (!args.approvalId || validId(args.approvalId)) && (!args.authorizedApp || validId(args.authorizedApp)), 400, 'Invalid computer arguments'); @@ -86,7 +88,10 @@ export class DesktopCapabilities { check(request.method === 'GET', 405, 'GET required'); const previous = this.providers.get(device.id); if (previous) { this.disconnect(previous); previous.response.destroy(); } - const provider = { id: randomUUID(), deviceId: device.id, machineId: `mac-${device.id}`, response, lastSeen: Date.now() }; + const requested = new URL(request.url, 'http://local').searchParams.get('platform') ?? 'darwin'; + check(Object.hasOwn(desktopPlatforms, requested), 400, 'Unsupported desktop platform'); + const provider = { id: randomUUID(), deviceId: device.id, platform: requested, + machineId: `${desktopPlatforms[requested]}-${device.id}`, response, lastSeen: Date.now() }; this.providers.set(device.id, provider); this.connections?.track(device.id, response); response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', 'x-accel-buffering': 'no' }); diff --git a/host/server/index.mjs b/host/server/index.mjs index 5a249baf394509012be0b985c442157ae63243d1..936a541c236b32052e0183ad918e02e3bf1c5bcb 100644 --- a/host/server/index.mjs +++ b/host/server/index.mjs @@ -51,6 +51,7 @@ import { attachmentDataUrl } from "./attachments.mjs"; import { DeviceConnections, proxyHttp, proxyWebSocket } from "./proxy.mjs"; import { proxyLocalExec } from "./local-exec-proxy.mjs"; import { VncTickets, vncPath, normalizeVncUpgradeUrl } from "./vnc.mjs"; +import { WebClient, rawBody, webManifest } from "./web-client.mjs"; import { adminMutation, bearer, @@ -68,7 +69,7 @@ import { const publicDir = fileURLToPath(new URL("./public/", import.meta.url)); const assetTypes = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml" }; -const pages = new Map([["/", "index.html"], ["/admin", "index.html"], ["/connectors/result", "connector-result.html"]]); +const pages = new Map([["/", "index.html"], ["/admin", "index.html"], ["/connectors/result", "connector-result.html"], ["/web/login", "web-login.html"]]); // Admin assets are served from a fixed listing taken at startup. const publicAssets = new Set(readdirSync(publicDir).filter((name) => [".js", ".css", ".svg"].includes(extname(name)))); const adminCookie = "grokbot_admin"; @@ -127,6 +128,7 @@ export async function createSelfHostServer(options = {}) { ), }; const auth = await new Auth(dataDir, options.authOptions).load(); + const webClient = await new WebClient(dataDir, { auth }).load(); const models = new Models(dataDir, { filename: options.modelFile ?? process.env.GROKBOT_MODEL_ENV, }); @@ -164,7 +166,7 @@ export async function createSelfHostServer(options = {}) { const desktopCapabilities = new DesktopCapabilities({ authenticate: device, connections, internalToken, enabled: () => harness.current().macComputer }); const browserProviders = new DesktopBrowserProviders({ authenticate: device, connections, hostUrl, internalToken, enabled: key => harness.current()[key] }); let executionRevision = executionNode.active()?.revision; - const limiter = new RateLimit(); + const limiter = options.rateLimit ?? new RateLimit(); const usage = timeZone => { try { new Intl.DateTimeFormat('en', { timeZone }).format(); } catch { throw new HttpError(400, 'Invalid time zone'); } @@ -173,8 +175,10 @@ export async function createSelfHostServer(options = {}) { const sockets = new Set(); function device(request) { check(federation.role() === 'primary', 403, 'Connect to the primary Host'); - const found = auth.authenticate(bearer(request)); - check(found, 401, "设备凭证无效,请重新配对"); + // The web client signs in with a cookie instead of a bearer token (web-client.mjs). + const browser = webClient.deviceToken(request, request.grokbotOrigin); + const found = auth.authenticate(browser ?? bearer(request)); + check(found && (!browser || found.platform === "web"), 401, "设备凭证无效,请重新配对"); void auth.touch(found.id).catch(() => {}); return found; } @@ -234,6 +238,68 @@ export async function createSelfHostServer(options = {}) { ticketCookie: `grokbot_vnc_${route.slot}=${ticket}; Path=/vnc/${route.slot}/; HttpOnly; SameSite=Strict; Max-Age=${Math.floor(tickets.ttlMs / 1000)}${origin.startsWith("https:") ? "; Secure" : ""}`, }; } + async function revokeDevice(id) { + await auth.revoke(id); + await push.revoke(id); + tickets.revoke(id); + connections.revoke(id); + } + /** Sign-in, sign-out and the bundle files of the web client (web-client.mjs); /web/login is a public page. */ + async function webRoutes(request, response, path, origin, url) { + const method = request.method; + const fromPage = () => check(request.headers["x-grokbot-web"] === "1" && + (!request.headers.origin || request.headers.origin === origin), 403, "请从网页版登录页操作"); + if (method === "GET" && path === "/web/api/session") { + const signedIn = webClient.browserDevice(request), status = webClient.status(); + return sendJson(response, 200, { available: status.available, rendererVersion: status.rendererVersion, + paired: Boolean(signedIn), deviceName: signedIn?.device.name ?? null, secure: origin.startsWith("https:") }); + } + if (method === "POST" && path === "/web/api/pair") { + check(federation.role() === "primary", 403, "Connect to the primary Host"); + fromPage(); + check(webClient.available, 404, "网页版未启用"); + limiter.check(`pair:${request.socket.remoteAddress}`, 6); + limiter.check("pair:global", 60); + const { pairingKey, deviceName } = await jsonBody(request); + const previous = webClient.browserDevice(request); + const result = await auth.pair({ pairingKey, deviceName }, { web: true }); + // Signing in again replaces this browser's earlier device instead of leaving it behind. + if (previous) await revokeDevice(previous.device.id); + response.setHeader("set-cookie", webClient.sessionCookie(result.token, origin)); + return sendJson(response, 201, { ok: true, deviceId: result.deviceId }); + } + if (method === "POST" && path === "/web/api/logout") { + fromPage(); + const signedIn = webClient.browserDevice(request); + if (signedIn) await revokeDevice(signedIn.device.id); + response.setHeader("set-cookie", webClient.sessionCookie("", origin)); + return sendJson(response, 200, { ok: true }); + } + if (method === "GET" && path === "/web/manifest.webmanifest") { + check(webClient.available, 404, "网页版未启用"); + response.writeHead(200, { "content-type": "application/manifest+json; charset=utf-8" }); + return response.end(JSON.stringify(webManifest())); + } + if (["GET", "HEAD"].includes(method) && (path === "/web" || path === "/web/")) { + response.writeHead(302, { location: `${webClient.browserDevice(request) ? "/web/renderer/index.html" : "/web/login"}${url.search}` }); + return response.end(); + } + const file = /^\/web\/((?:renderer|client)\/.+)$/.exec(path); + if (file && ["GET", "HEAD"].includes(method)) { + let name = null; + try { name = decodeURIComponent(file[1]); } catch {} + check(name && webClient.has(name), 404, "文件不存在"); + const signedIn = webClient.browserDevice(request); + if (!signedIn && name === "renderer/index.html") { + response.writeHead(302, { location: `/web/login${url.search}` }); + return response.end(); + } + check(signedIn, 401, "请先登录网页版"); + void auth.touch(signedIn.device.id).catch(() => {}); + return webClient.serve(request, response, name); + } + throw new HttpError(404, "页面不存在"); + } async function hostStatus() { try { const result = await fetch(new URL("/api/listAgents", hostUrl), { @@ -274,11 +340,9 @@ export async function createSelfHostServer(options = {}) { validateAgentId(agentId); const status = await hostStatus(); check(status.connected, 503, "Host 暂不可用,无法读取 Bot 资料库"); - check( - status.agents.some((agent) => agent.id === agentId), - 404, - "Bot 不存在", - ); + const agent = status.agents.find((item) => item.id === agentId); + check(agent, 404, "Bot 不存在"); + return agent; } async function adminRoutes(request, response, path, origin) { const method = request.method; @@ -358,9 +422,11 @@ export async function createSelfHostServer(options = {}) { startedAt: bootAt, publicUrl: origin, model, - host, + host: { ...host, waitingForExecutionNode: !host.connected && + process.env.GROKBOT_REQUIRE_EXECUTION_NODE === '1' && !executionNode.store.value.config.enabled }, devices: push.devices(), pairingKeys: auth.pairingKeys(), + webClient: webClient.status(), notifications: { ...notificationSettings.current(), count: notifications.store.value.items.length, @@ -400,8 +466,37 @@ export async function createSelfHostServer(options = {}) { await models.test(await jsonBody(request)), ); } + const summarize = /^\/admin\/api\/agents\/([a-f0-9-]{1,128})\/summarize$/.exec(path); + if (method === 'POST' && summarize) { + const agent = await verifyAgent(summarize[1]); + check(!agent.isRunning, 409, 'Bot 正在运行,请在任务结束后再压缩'); + limiter.check(`manual-summary:${summarize[1]}`, 4, 10 * 60_000); + const result = await internalHostClient(hostUrl, internalToken)('localApplicationRpc', { + action: 'grokbot.manual-summary', agentId: summarize[1], + }); + return sendJson(response, 200, { ...result, message: '上下文已压缩' }); + } if (method === "POST" && path === "/admin/api/pairing-keys") return sendJson(response, 201, await auth.createPairing()); + if (path === "/admin/api/web-client") { + if (method === "GET") return sendJson(response, 200, webClient.status()); + if (method === "PUT") { + check(String(request.headers["content-type"] ?? "").split(";")[0].trim() === "application/zip", 415, "请上传 ZIP 格式的网页版界面包"); + return sendJson(response, 200, await webClient.install(await rawBody(request))); + } + if (method === "PATCH") return sendJson(response, 200, await webClient.setEnabled((await jsonBody(request)).enabled)); + if (method === "DELETE") return sendJson(response, 200, await webClient.remove()); + } + if (method === "POST" && path === "/admin/api/web-client/open") { + // Opens the web client in the administrator's own browser without a pairing code. + check(webClient.available, 409, "请先上传并启用网页版"); + const { deviceName } = await jsonBody(request); + // A browser that is already signed in keeps its device instead of gaining another. + if (webClient.browserDevice(request)) return sendJson(response, 200, { ok: true, url: "/web/" }); + const result = await auth.addWebDevice(typeof deviceName === "string" && deviceName.trim() ? deviceName : "网页版"); + response.setHeader("set-cookie", webClient.sessionCookie(result.token, origin)); + return sendJson(response, 201, { ok: true, url: "/web/" }); + } const deviceName = /^\/admin\/api\/devices\/([a-f0-9-]{36})$/.exec(path); if (method === "PATCH" && deviceName) { const body = await jsonBody(request); @@ -411,10 +506,7 @@ export async function createSelfHostServer(options = {}) { path, ); if (method === "POST" && revoke) { - await auth.revoke(revoke[1]); - await push.revoke(revoke[1]); - tickets.revoke(revoke[1]); - connections.revoke(revoke[1]); + await revokeDevice(revoke[1]); return sendJson(response, 200, { ok: true }); } if (path === '/admin/api/notification-settings' && ['GET', 'PUT'].includes(method)) @@ -459,9 +551,17 @@ export async function createSelfHostServer(options = {}) { const path = request.url.split("?")[0]; const origin = originFor(request, network.isIngress(request) ? '' : canonical); delete request.headers['x-grokbot-tailcat-ingress']; + request.grokbotOrigin = origin; const url = new URL(request.url, origin); if (path.startsWith("/admin/api/")) return adminRoutes(request, response, path, origin); + if ((path === "/web" || path.startsWith("/web/")) && path !== "/web/login") + return webRoutes(request, response, path, origin, url); + if (path === "/local-client/icon.png" && request.method === "GET") { + // The desktop settings pages load the program icon from here; the web client serves its own. + check(webClient.browserDevice(request) && webClient.has("client/icon.png"), 404, "页面不存在"); + return webClient.serve(request, response, "client/icon.png"); + } if (await mediaInternal(request, response, path, { internalToken, mediaServices, webServices })) return; if (request.method === 'POST' && ['/federation/v1/pair', '/federation/v1/sync', '/federation/v1/revoke'].includes(path)) { limiter.check(`federation:${request.socket.remoteAddress}`, 120); @@ -577,9 +677,21 @@ export async function createSelfHostServer(options = {}) { } if (path.startsWith("/vnc/")) { check(["GET", "HEAD"].includes(request.method), 405, "不支持的请求方法"); + // The web client's computer view runs the bridge the Android shell injects (android/client/vnc-bridge.js). + const script = /^\/vnc\/(desktop|fork)\/__grokbot-(vnc-bridge|vnc-preload)\.js$/.exec(path); + if (script) { + const value = tickets.validate(cookie(request, `grokbot_vnc_${script[1]}`), script[1]); + check(value && webClient.available && auth.device(value.deviceId)?.platform === "web", 401, "桌面访问票据已失效,请重新打开电脑预览"); + const body = await webClient.vncScript(script[2], origin); + response.writeHead(200, { "content-type": "text/javascript; charset=utf-8", "cross-origin-resource-policy": "same-origin" }); + return response.end(request.method === "HEAD" ? undefined : body); + } const access = vncAccess(request, url, path, origin); connections.track(access.deviceId, response); - return proxyHttp(request, response, access); + const page = request.method === "GET" && /^\/vnc\/(desktop|fork)\/vnc(_lite|_auto)?\.html$/.test(path); + const web = page && webClient.available && auth.device(access.deviceId)?.platform === "web"; + return proxyHttp(request, response, web + ? { ...access, transformHtml: html => WebClient.injectVncBridge(html, path.slice(0, path.lastIndexOf("/"))) } : access); } if (await desktopCapabilities.route(request, response, path)) return; if (await browserProviders.route(request, response, path)) return; @@ -609,7 +721,7 @@ export async function createSelfHostServer(options = {}) { const status = options.computers?.() ?? { available: false, computers: [] }, computers = new Map(status.computers.map(item => [item.id, item])); for (const item of desktopCapabilities.list()) { const previous = computers.get(item.machineId); - computers.set(item.machineId, { ...previous, id: item.machineId, label: item.label, connected: true, platform: 'darwin', + computers.set(item.machineId, { ...previous, id: item.machineId, label: item.label, connected: true, platform: item.platform ?? 'darwin', capabilities: [...new Set([...(previous?.capabilities ?? []), 'gui'])] }); } return sendJson(response, 200, { available: status.available || computers.size > 0, computers: [...computers.values()] }); @@ -766,6 +878,7 @@ export async function createSelfHostServer(options = {}) { ); const origin = originFor(request, network.isIngress(request) ? '' : canonical); delete request.headers['x-grokbot-tailcat-ingress']; + request.grokbotOrigin = origin; const url = new URL(request.url, origin); check(federation.role() === 'primary', 403, 'Connect to the primary Host'); if (url.pathname === '/local/voice/realtime') return voice.upgrade(request, socket, head); @@ -802,6 +915,7 @@ export async function createSelfHostServer(options = {}) { tickets, library, profile, + webClient, dataDir, async start( port = Number(process.env.GROKBOT_PORT ?? 8000), @@ -845,6 +959,7 @@ export async function createSelfHostServer(options = {}) { webhooks.store.tail, sharing.store.tail, mediaSettings.store.tail, webSettings.store.tail, mediaServices.store.tail, + webClient.store.tail, webClient.installing, ]); }, }; diff --git a/host/server/internal-host.mjs b/host/server/internal-host.mjs index c5d77d3978a4a9443d2affbff988c3562b5b6b81..e49a764baa23f9240258685a46e1ac707cdee756 100644 --- a/host/server/internal-host.mjs +++ b/host/server/internal-host.mjs @@ -2,9 +2,10 @@ import { HttpError } from './security.mjs'; export function internalHostClient(url, token) { return async (method, args, { signal } = {}) => { if (!/^[A-Za-z][A-Za-z0-9]+$/.test(method)) throw new Error('Invalid Host method'); + const manualSummary = method === 'localApplicationRpc' && args?.action === 'grokbot.manual-summary'; const response = await fetch(new URL(`/api/${method}`, url), { method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, - body: JSON.stringify(args), signal: signal ?? AbortSignal.timeout(method === 'localApplicationRpc' ? 110000 : 30000) }); + body: JSON.stringify(args), signal: signal ?? AbortSignal.timeout(manualSummary ? 300000 : method === 'localApplicationRpc' ? 110000 : 30000) }); const result = await response.json(); if (!response.ok) throw new HttpError(response.status, result.error ?? 'Host request failed'); return result; diff --git a/host/server/media-http.mjs b/host/server/media-http.mjs index d5ee5327dbcf5fabf341402df214efd8d5f6a280..92a64c9f65715ae0e1d7d3805054c7b2e86fdbc4 100644 --- a/host/server/media-http.mjs +++ b/host/server/media-http.mjs @@ -20,12 +20,13 @@ export async function boundedBody(response, limit = 8 * 1024 * 1024) { return Buffer.concat(parts); } catch (error) { response.destroy?.(); throw error; } } -export async function serviceJson(url, { apiKey, signal, body, method, limit } = {}) { - const response = await fetch(url, { method: method ?? (body === undefined ? 'GET' : 'POST'), +/** `form` sends multipart FormData (fetch sets the boundary); `body` sends JSON. */ +export async function serviceJson(url, { apiKey, signal, body, form, method, limit } = {}) { + const response = await fetch(url, { method: method ?? (body === undefined && form === undefined ? 'GET' : 'POST'), redirect: 'error', signal, headers: { accept: 'application/json', ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + ...(form !== undefined ? { body: form } : body === undefined ? {} : { body: JSON.stringify(body) }) }); if (!response.ok) { await response.body?.cancel(); throw Object.assign(new HttpError(502, `Service returned HTTP ${response.status}`), { upstreamStatus: response.status }); diff --git a/host/server/media-providers.mjs b/host/server/media-providers.mjs index 88f2168248b139e58ef4ff65524ec261907717d0..08468bf59ad10f5cdfba65cb40f8b29b3562de81 100644 --- a/host/server/media-providers.mjs +++ b/host/server/media-providers.mjs @@ -8,15 +8,36 @@ function reference(value) { && value.data.length < 40 * 1024 * 1024 && /^[A-Za-z0-9+/]+={0,2}$/.test(value.data), 400, 'Invalid reference image'); return `data:${value.mimeType};base64,${value.data}`; } -export function mediaInput(model, input) { +// Sizes every OpenAI-compatible image model accepts. +const standardSizes = ['1024x1024', '1536x1024', '1024x1536']; +/** The WIDTHxHEIGHT entry whose ratio is closest to `aspectRatio`; earlier entries win ties. */ +export function sizeForAspect(aspectRatio, sizes = standardSizes) { + const [width, height] = aspectRatio.split(':').map(Number); + check(width > 0 && height > 0, 400, 'Invalid aspect ratio'); + let best; + for (const size of sizes) { + const match = /^(\d+)x(\d+)$/.exec(size); + if (!match) continue; + const distance = Math.abs(Math.log((match[1] / match[2]) / (width / height))); + if (!best || distance < best.distance - 1e-9) best = { size, distance }; + } + check(best, 400, 'No configured size matches the aspect ratio'); + return best.size; +} +export function mediaInput(model, input, adapter) { check(typeof input.prompt === 'string' && input.prompt.trim().length > 0 && input.prompt.length <= 30_000, 400, 'Invalid media prompt'); check(!input.references || Array.isArray(input.references) && input.references.length <= 10, 400, 'Too many reference images'); const body = { ...model.parameters, prompt: input.prompt }; const properties = model.inputSchema?.properties; if (input.aspectRatio) { check(typeof input.aspectRatio === 'string' && /^\d{1,2}:\d{1,2}$/.test(input.aspectRatio), 400, 'Invalid aspect ratio'); - check(!properties || properties.aspect_ratio, 400, 'This model does not accept aspect_ratio; configure its size parameter'); - body.aspect_ratio = input.aspectRatio; + // Models that take a pixel size instead of a ratio get the closest listed size; explicit parameters still win below. + const sizes = Array.isArray(properties?.size?.enum) ? properties.size.enum : adapter === 'openai-images' ? standardSizes : null; + if (sizes && !properties?.aspect_ratio) body.size = sizeForAspect(input.aspectRatio, sizes); + else { + check(!properties || properties.aspect_ratio, 400, 'This model does not accept aspect_ratio; configure its size parameter'); + body.aspect_ratio = input.aspectRatio; + } } if (input.references?.length) { const images = input.references.map(reference); @@ -43,11 +64,23 @@ export async function submitMedia(provider, model, body, signal) { return waveResult(await serviceJson(`${provider.baseUrl}/api/v3/${model.model}`, { ...common, body })); } if (provider.adapter === 'openai-images') { - check(!body.images?.length, 400, 'Configure an editing adapter for image references'); - const { aspect_ratio, ...parameters } = body; + const { aspect_ratio, images, image, ...parameters } = body; check(!aspect_ratio, 400, 'OpenAI Images uses the configured size parameter'); - const result = await serviceJson(`${provider.baseUrl}/images/generations`, { - ...common, body: { ...parameters, model: model.model, n: 1 } }); + const request = { ...parameters, model: model.model, n: 1 }, references = images ?? (image ? [image] : []); + let result; + if (references.length) { + // Reference images go to the edits endpoint as multipart files. + const form = new FormData(); + for (const [key, value] of Object.entries(request)) { + check(value === null || ['string', 'number', 'boolean'].includes(typeof value), 400, `Image edits do not accept parameter ${key}`); + if (value !== null) form.append(key, String(value)); + } + references.forEach((url, index) => { + const [, mimeType, data] = /^data:(image\/[a-z]+);base64,(.*)$/.exec(url); + form.append('image[]', new Blob([Buffer.from(data, 'base64')], { type: mimeType }), `reference-${index + 1}.${mimeType.slice(6)}`); + }); + result = await serviceJson(`${provider.baseUrl}/images/edits`, { ...common, form }); + } else result = await serviceJson(`${provider.baseUrl}/images/generations`, { ...common, body: request }); check(Array.isArray(result.data) && result.data.length, 502, 'Image service returned no image'); return { status: 'completed', outputs: result.data.map(item => item.b64_json ? { base64: item.b64_json, mimeType: 'image/png' } : item.url) }; diff --git a/host/server/media-settings.mjs b/host/server/media-settings.mjs index 95114295fc6b0d0eaaa2b4878aa488fd2bb3b365..29ae73e9aa3648ac26be8d6fb9283969e880be6f 100644 --- a/host/server/media-settings.mjs +++ b/host/server/media-settings.mjs @@ -69,7 +69,7 @@ export function mediaModels(config, kind) { export function describeMediaModels(models) { return models.map(model => { const parameters = Object.fromEntries(Object.entries(model.inputSchema?.properties ?? {}) - .filter(([name]) => !['prompt', 'enable_sync_mode', 'enable_base64_output'].includes(name)) + .filter(([name]) => !['prompt', 'images', 'image', 'enable_sync_mode', 'enable_base64_output'].includes(name)) .map(([name, schema]) => [name, Object.fromEntries(['type', 'enum', 'minimum', 'maximum', 'maxItems', 'default'] .filter(key => schema?.[key] !== undefined).map(key => [key, schema[key]]))])); return `${model.id}: ${model.name}. ${model.description}` diff --git a/host/server/models.mjs b/host/server/models.mjs index 88ab5abf11a2cedc3b1cd581edb9ca50d717ef4e..e0228d259ee895f4cab95d75f27dbd2f69ef9e5f 100644 --- a/host/server/models.mjs +++ b/host/server/models.mjs @@ -1,220 +1,264 @@ -import { parseModelPolicy, defaultPolicy, validatePolicy, effortLevels, reasoningOptions } from '../runtime/model-policy.mjs'; +import { catalogContextPolicy, defaultPolicy, effortLevels, parseModelPolicy, validatePolicy, EFFORTS } from '../runtime/model-policy.mjs'; import { createModelRouter } from '../runtime/model-router.mjs'; +import { anthropicEndpoint, anthropicHeaders } from '../runtime/anthropic-messages.mjs'; +import { createModelSession } from '../runtime/model-session.mjs'; +import { API_FORMATS, MODEL_ROUTING_ENV, isConfiguredModelRouting, modelRouteForAgent, modelRouteForProfile, + parseModelRouting, publicModelRouting, validateModelProvider, validateModelRouting } from '../runtime/model-routing.mjs'; import { recordUsage } from '../runtime/usage-ledger.mjs'; -import { randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import { join } from "node:path"; -import { check } from "./security.mjs"; -import { readJson, writePrivate } from "./storage.mjs"; +import { randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { check } from './security.mjs'; +import { readJson, writePrivate } from './storage.mjs'; +const own = (value, key) => Object.prototype.hasOwnProperty.call(value ?? {}, key); const clean = (value, label, maximum = 2048) => { - check( - typeof value === "string" && - value.trim().length > 0 && - value.length <= maximum && - !/[\r\n\0]/.test(value), - 400, - `${label}不能为空,也不能包含换行`, - ); + check(typeof value === 'string' && value.trim().length > 0 && value.length <= maximum && !/[\r\n\0]/.test(value), 400, + `${label}不能为空,也不能包含换行`); return value.trim(); }; + +function valuesFrom(source) { + return Object.fromEntries(source.split(/\r?\n/).filter(line => line.includes('=') && !line.startsWith('#')) + .map(line => { const at = line.indexOf('='); return [line.slice(0, at), line.slice(at + 1)]; })); +} + +function legacyConfig(values) { + return { + apiFormat: API_FORMATS.includes(values.MODEL_API_FORMAT) ? values.MODEL_API_FORMAT : 'openai', + baseUrl: values.OPENAI_BASE_URL ?? '', model: values.OPENAI_MODEL ?? '', apiKey: values.OPENAI_API_KEY ?? '', + contextWindowTokens: Number(values.OPENAI_CONTEXT_WINDOW_TOKENS ?? 0), + policy: parseModelPolicy(values.GROKBOT_MODEL_POLICY, values.OPENAI_MODEL || undefined), + jevApiKey: values.JEV_API_KEY || '', + }; +} + +function context(value) { + const parsed = Number(value ?? 0); + check(Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= 100_000_000, 400, + '上下文长度应为 0–100000000 的整数'); + return parsed; +} + +function serviceUrl(value) { + const baseUrl = clean(value, 'Base URL'); + let url; + try { url = new URL(baseUrl); } + catch { check(false, 400, 'Base URL 格式不正确'); } + check(['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash, + 400, 'Base URL 需要 HTTP(S) 地址,不能包含凭证或查询参数'); + return url.href.replace(/\/$/, ''); +} + +function publicError(error) { + return `模型配置无效:${String(error?.message ?? error).slice(0, 240)}`; +} + +function compatibilityPolicy(route) { + const policy = defaultPolicy(route.model); + policy.effort = route.effort; + policy.models = [{ id: route.model, efforts: route.efforts, + contextWindowTokens: route.contextWindowTokens, summaryThresholdTokens: route.summaryThresholdTokens }]; + return policy; +} + export class Models { - constructor(dataDir, { filename = join(dataDir, "model.env") } = {}) { + constructor(dataDir, { filename = join(dataDir, 'model.env') } = {}) { this.filename = filename; this.dataDir = dataDir; this.tail = Promise.resolve(); } async current() { - const filename = this.filename; - const source = await readFile(filename, "utf8").catch((error) => { - if (error.code === "ENOENT") return ""; + const source = await readFile(this.filename, 'utf8').catch(error => { + if (error.code === 'ENOENT') return ''; throw error; }); - const values = Object.fromEntries( - source - .split(/\r?\n/) - .filter((line) => line.includes("=") && !line.startsWith("#")) - .map((line) => { - const at = line.indexOf("="); - return [line.slice(0, at), line.slice(at + 1)]; - }), - ); - return { - baseUrl: values.OPENAI_BASE_URL ?? "", - model: values.OPENAI_MODEL ?? "", - apiKey: values.OPENAI_API_KEY ?? "", - contextWindowTokens: Number(values.OPENAI_CONTEXT_WINDOW_TOKENS ?? 0), - policy: parseModelPolicy(values.GROKBOT_MODEL_POLICY, values.OPENAI_MODEL || undefined), - jevApiKey: values.JEV_API_KEY || "", - }; + const values = valuesFrom(source), legacy = legacyConfig(values); + const parsed = parseModelRouting(values[MODEL_ROUTING_ENV], legacy); + let primary; + try { primary = modelRouteForAgent(parsed.config); } + catch { primary = undefined; } + return { ...legacy, routing: parsed.config, routingMigrated: parsed.migrated, + legacyAdaptiveRouting: parsed.migrated && legacy.policy?.mode === 'adaptive', + ...(primary ? { baseUrl: primary.baseUrl, apiKey: primary.apiKey, apiFormat: primary.apiFormat, + model: primary.model, contextWindowTokens: primary.contextWindowTokens, policy: compatibilityPolicy(primary) } : {}) }; } async publicConfig() { - const { apiKey, jevApiKey, ...config } = await this.current(); + const current = await this.current(); + const { apiKey, jevApiKey, routing, ...summary } = current; return { - ...config, - hasApiKey: Boolean(apiKey), - hasJevApiKey: Boolean(jevApiKey), - configured: Boolean(config.baseUrl && config.model && apiKey), + ...publicModelRouting(routing), + ...summary, + hasApiKey: Boolean(apiKey), hasJevApiKey: Boolean(jevApiKey), + configured: isConfiguredModelRouting(routing), reload: await this.reloadStatus(), }; } async reloadStatus() { - const request = await readJson( - join(this.dataDir, "model-reload-request.json"), - null, - ); - const status = await readJson( - join(this.dataDir, "model-reload-status.json"), - null, - ); - if (!request) return status ?? { status: "none" }; + const request = await readJson(join(this.dataDir, 'model-reload-request.json'), null); + const status = await readJson(join(this.dataDir, 'model-reload-status.json'), null); + if (!request) return status ?? { status: 'none' }; if (status?.revision === request.revision) { - const allowed = ["applied", "waiting", "error", "pending"]; - return { - revision: status.revision, - status: allowed.includes(status.status) ? status.status : "pending", - updatedAt: status.updatedAt, - message: - status.status === "error" - ? "Host 未能应用配置,请检查服务日志" - : undefined, - }; + const allowed = ['applied', 'waiting', 'error', 'pending']; + return { revision: status.revision, status: allowed.includes(status.status) ? status.status : 'pending', + updatedAt: status.updatedAt, message: status.status === 'error' ? 'Host 未能应用配置,请检查服务日志' : undefined }; } - return { - revision: request.revision, - status: "pending", - updatedAt: request.requestedAt, - }; + return { revision: request.revision, status: 'pending', updatedAt: request.requestedAt }; } - async validated(input) { - const previous = await this.current(); - const baseUrl = clean(input.baseUrl, "Base URL"); - let url; + legacyRouting(input, previous) { + const apiFormat = input.apiFormat ?? previous.apiFormat; + check(API_FORMATS.includes(apiFormat), 400, '接口格式无效'); + const baseUrl = serviceUrl(input.baseUrl ?? previous.baseUrl); + const model = clean(input.model ?? previous.model, '模型名称', 256); + const active = (() => { try { return modelRouteForAgent(previous.routing); } catch { return undefined; } })(); + const apiKey = clean(input.apiKey || active?.apiKey || previous.apiKey, 'API Key', 8192); + const contextWindowTokens = context(input.contextWindowTokens ?? active?.contextWindowTokens ?? previous.contextWindowTokens); + let policy; try { - url = new URL(baseUrl); - } catch { - check(false, 400, "Base URL 格式不正确"); + policy = validatePolicy(input.policy ?? (previous.model === model ? previous.policy : defaultPolicy(model)), model); + } catch (error) { check(false, 400, error.message); } + check(policy.mode !== 'adaptive' || (input.jevApiKey || previous.jevApiKey), 400, '请填写 Jev API Key'); + const providerId = active?.providerId ?? 'default', profileId = active?.profileId ?? 'default'; + const capability = policy.models.find(item => item.id === model) ?? { efforts: effortLevels(model) }; + const providers = (previous.routing.providers ?? []).filter(item => item.id !== providerId); + providers.push({ id: providerId, name: active?.providerName ?? '默认服务', apiFormat, baseUrl, apiKey }); + const profiles = (previous.routing.profiles ?? []).filter(item => item.id !== profileId); + profiles.push({ id: profileId, name: active?.profileName ?? '默认模型', providerId, model, + efforts: capability.efforts, contextWindowTokens: capability.contextWindowTokens ?? contextWindowTokens, + summaryThresholdTokens: capability.summaryThresholdTokens ?? 0 }); + let routing; + try { + routing = validateModelRouting({ version: 1, providers, profiles, + defaultRoute: { profileId, effort: policy.effort, fallbacks: previous.routing.defaultRoute?.fallbacks ?? [] }, + botRoutes: previous.routing.botRoutes ?? {} }, { previous: previous.routing }); + } catch (error) { check(false, 400, publicError(error)); } + return { routing, jevApiKey: input.jevApiKey ? clean(input.jevApiKey, 'Jev API Key', 8192) : previous.jevApiKey, + ...(previous.routingMigrated ? { legacy: { apiFormat, baseUrl, apiKey, model, contextWindowTokens, policy } } : {}) }; + } + async validated(input = {}) { + check(input && typeof input === 'object' && !Array.isArray(input), 400, '模型配置无效'); + const previous = await this.current(); + const multiProvider = Array.isArray(input.providers) || own(input, 'defaultRoute') || input.version === 1; + if (!multiProvider) return this.legacyRouting(input, previous); + check(!previous.routingMigrated || input.migrateLegacyRouting === true, 409, + '检测到旧版模型配置。请在模型页确认迁移后再保存。'); + let routing; + try { routing = validateModelRouting(input, { previous: previous.routing }); } + catch (error) { check(false, 400, publicError(error)); } + return { routing, jevApiKey: input.jevApiKey ? clean(input.jevApiKey, 'Jev API Key', 8192) : previous.jevApiKey }; + } + async write(config) { + if (config.legacy) { + const { apiFormat, baseUrl, apiKey, model, contextWindowTokens, policy } = config.legacy; + await writePrivate(this.filename, [ + `MODEL_API_FORMAT=${apiFormat}`, + `OPENAI_BASE_URL=${baseUrl}`, + `OPENAI_API_KEY=${apiKey}`, + `OPENAI_MODEL=${model}`, + `OPENAI_CONTEXT_WINDOW_TOKENS=${contextWindowTokens}`, + `GROKBOT_MODEL_POLICY=${JSON.stringify(policy)}`, + `JEV_API_KEY=${config.jevApiKey}`, + '', + ].join('\n')); + return; } - check( - ["http:", "https:"].includes(url.protocol) && - !url.username && - !url.password && - !url.search && - !url.hash, - 400, - "Base URL 需要 HTTP(S) 地址,不能包含凭证或查询参数", - ); - const model = clean(input.model, "模型名称", 256); - const apiKey = clean(input.apiKey || previous.apiKey, "API Key", 8192); - const contextWindowTokens = Number( - input.contextWindowTokens ?? previous.contextWindowTokens ?? 0, - ); - check( - Number.isSafeInteger(contextWindowTokens) && - contextWindowTokens >= 0 && - contextWindowTokens <= 100_000_000, - 400, - "上下文长度应为 0–100000000 的整数", - ); - let policy; - try { policy = validatePolicy(input.policy ?? (previous.model === model ? previous.policy : defaultPolicy(model)), model); } - catch (error) { check(false, 400, error.message); } - const jevApiKey = input.jevApiKey ? clean(input.jevApiKey, "Jev API Key", 8192) : previous.jevApiKey; - check(policy.mode !== 'adaptive' || jevApiKey, 400, '请填写 Jev API Key'); - return { - policy, jevApiKey, - baseUrl: url.href.replace(/\/$/, ""), - model, - apiKey, - contextWindowTokens, - }; + const primary = modelRouteForAgent(config.routing); + const policy = compatibilityPolicy(primary); + await writePrivate(this.filename, [ + `${MODEL_ROUTING_ENV}=${JSON.stringify(config.routing)}`, + `MODEL_API_FORMAT=${primary.apiFormat}`, + `OPENAI_BASE_URL=${primary.baseUrl}`, + `OPENAI_API_KEY=${primary.apiKey}`, + `OPENAI_MODEL=${primary.model}`, + `OPENAI_CONTEXT_WINDOW_TOKENS=${primary.contextWindowTokens}`, + `GROKBOT_MODEL_POLICY=${JSON.stringify(policy)}`, + `JEV_API_KEY=${config.jevApiKey}`, + '', + ].join('\n')); } save(input) { const pending = this.tail.then(async () => { const config = await this.validated(input); - await writePrivate( - this.filename, - [ - `OPENAI_BASE_URL=${config.baseUrl}`, - `OPENAI_API_KEY=${config.apiKey}`, - `OPENAI_MODEL=${config.model}`, - `OPENAI_CONTEXT_WINDOW_TOKENS=${config.contextWindowTokens}`, - `GROKBOT_MODEL_POLICY=${JSON.stringify(config.policy)}`, - `JEV_API_KEY=${config.jevApiKey}`, - "", - ].join("\n"), - ); - const request = { - revision: randomUUID(), - requestedAt: new Date().toISOString(), - }; - await writePrivate( - join(this.dataDir, "model-reload-request.json"), - `${JSON.stringify(request)}\n`, - ); + await this.write(config); + const request = { revision: randomUUID(), requestedAt: new Date().toISOString() }; + await writePrivate(join(this.dataDir, 'model-reload-request.json'), `${JSON.stringify(request)}\n`); return this.publicConfig(); }); this.tail = pending.catch(() => {}); return pending; } - async catalog(input) { + async routeFor(input = {}, { profileId, direct = false } = {}) { + const hasConfig = Array.isArray(input.providers) || own(input, 'defaultRoute') || input.version === 1 || own(input, 'baseUrl'); + const config = hasConfig ? await this.validated(input) : { routing: (await this.current()).routing }; + if (profileId) return { config, route: modelRouteForProfile(config.routing, profileId) }; + const route = modelRouteForAgent(config.routing); + return { config, route: direct ? { ...route, fallbacks: [] } : route }; + } + async catalog(input = {}) { const previous = await this.current(); - const config = await this.validated({ ...previous, ...input }); + let provider; + if (input.provider) { + try { provider = validateModelProvider(input.provider, { previous: previous.routing }); } + catch (error) { check(false, 400, publicError(error)); } + } else if (input.providerId && !Array.isArray(input.providers) && !own(input, 'baseUrl')) { + provider = previous.routing.providers.find(item => item.id === input.providerId); + check(provider, 404, '模型服务不存在'); + } else { + const { route } = await this.routeFor(input, { profileId: input.profileId, direct: true }); + provider = route; + } let response; - try { response = await fetch(`${config.baseUrl}/models`, { redirect: 'error', - headers: { authorization: `Bearer ${config.apiKey}` }, signal: AbortSignal.timeout(15000) }); } - catch { check(false, 502, '无法读取模型列表'); } + const anthropic = provider.apiFormat === 'anthropic'; + try { + response = await fetch(anthropic ? anthropicEndpoint(provider.baseUrl, 'models') : `${provider.baseUrl}/models`, { + redirect: 'error', headers: anthropic ? anthropicHeaders(provider.apiKey) : { authorization: `Bearer ${provider.apiKey}` }, + signal: AbortSignal.timeout(15_000), + }); + } catch { check(false, 502, '无法读取模型列表'); } check(response.ok, 502, `Model catalog HTTP ${response.status}`); const body = await response.json(); check(Array.isArray(body.data), 502, '模型列表格式不兼容'); - return { models: body.data.filter(item => typeof item.id === 'string').slice(0, 100).map(item => { - const supplied = item.supported_reasoning_efforts ?? item.reasoning_effort?.values ?? item.capabilities?.reasoning_efforts; - const levels = Array.isArray(supplied) ? supplied.filter(level => ['none','low','medium','high','xhigh','max'].includes(level)) : null; - return { id: item.id, efforts: levels ?? effortLevels(item.id), source: levels ? 'provider' : effortLevels(item.id).length ? 'reference' : 'manual' }; + return { models: body.data.filter(item => typeof item.id === 'string').slice(0, 200).map(item => { + const supplied = item.supported_reasoning_efforts ?? item.supported_efforts ?? item.reasoning_effort?.values ?? item.capabilities?.reasoning_efforts; + const levels = Array.isArray(supplied) ? EFFORTS.filter(level => supplied.includes(level)) : null; + const capacity = [item.context_window, item.max_input_tokens, item.context_length] + .find(value => Number.isSafeInteger(value) && value > 0 && value <= 100_000_000); + return { id: item.id, efforts: levels ?? effortLevels(item.id), source: levels ? 'provider' : effortLevels(item.id).length ? 'reference' : 'manual', + ...catalogContextPolicy(item.id, capacity) }; }) }; } async classify(input) { - const config = await this.validated(input); + const current = await this.current(); + const base = { ...current, ...(input ?? {}) }; + const config = await this.legacyRouting(base, current); + const route = modelRouteForAgent(config.routing); check(config.jevApiKey, 400, '请填写 Jev API Key'); - const route = createModelRouter({ ...config, policy: { ...config.policy, mode: 'adaptive' }, usageDirectory: join(this.dataDir, 'usage'), routingDirectory: join(this.dataDir, 'routing'), routingSource: 'test' }); - const decision = await route({ messages: [{ role: 'user', content: clean(input.task, '任务', 10000) }] }); - const { requestOptions, ...result } = decision; + const policy = { ...compatibilityPolicy(route), mode: 'adaptive' }; + const router = createModelRouter({ ...route, policy, jevApiKey: config.jevApiKey, + usageDirectory: join(this.dataDir, 'usage'), routingDirectory: join(this.dataDir, 'routing'), routingSource: 'test' }); + const decision = await router({ messages: [{ role: 'user', content: clean(input.task, '任务', 10000) }] }); + const { requestOptions, apiKey, baseUrl, ...result } = decision; return result; } - async test(input) { - const config = await this.validated(input); - let response; + async test(input = {}) { + const { config, route } = await this.routeFor(input, { profileId: input.profileId, direct: true }); + let usage; + const session = createModelSession({ ...route, policy: compatibilityPolicy(route), + onUsage: async value => { usage = value; }, selectRequest: async () => ({ ...route, fallbacks: [] }) }); + const result = session.getExecutor([{ role: 'user', content: 'Reply with OK.' }]) + .stream({ signal: AbortSignal.timeout(120_000) }, 'model-test', []); + let text = ''; try { - response = await fetch(`${config.baseUrl}/chat/completions`, { - method: "POST", - headers: { - "content-type": "application/json", - authorization: `Bearer ${config.apiKey}`, - }, - body: JSON.stringify({ - ...reasoningOptions(config.model, config.policy.effort), - model: config.model, - messages: [{ role: "user", content: "Reply with OK." }], - max_tokens: 1024, - stream: false, - }), - signal: AbortSignal.timeout(60_000), - redirect: "error", - }); - } catch { - check(false, 502, "模型服务连接失败或超时,请检查地址与网络"); - } - if (!response.ok) { - await response.body?.cancel(); - check( - false, - 502, - `模型服务返回 HTTP ${response.status},请检查模型名称和 API Key`, - ); + for await (const part of result.fullStream) if (part.type === 'text-delta') text += part.textDelta; + await result.response; + } catch (error) { + check(false, 502, error.name === 'TimeoutError' || error.name === 'AbortError' ? '模型服务连接超时,请检查地址与网络' + : error.status ? `模型服务返回 HTTP ${error.status}:${String(error.message).slice(0, 300)}` + : `模型请求失败:${String(error.message).slice(0, 300)}`); + } finally { + if (usage) await recordUsage(join(this.dataDir, 'usage'), { ...usage, kind: 'test' }).catch(() => {}); } - const body = await response.json().catch(() => null); - check(body?.choices?.length, 502, "模型服务返回的格式不兼容"); - await recordUsage(join(this.dataDir, 'usage'), { raw: body.usage, model: body.model ?? config.model, kind: 'test', requestId: body.id }); - return { ok: true, model: config.model, message: "模型接口已完成真实请求" }; + check(text.trim(), 502, '模型没有返回文字内容'); + return { ok: true, profileId: route.profileId, model: route.model, message: '模型接口已完成真实请求' }; } } diff --git a/host/server/package-lock.json b/host/server/package-lock.json index e8e1a0eda9a8794f980262290ea790f696afb296..404ebbcc8aa878ffa3a937fc473f57acb5abb902 100644 --- a/host/server/package-lock.json +++ b/host/server/package-lock.json @@ -14,9 +14,9 @@ } }, "node_modules/@hono/node-server": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.5.tgz", - "integrity": "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==", + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.9.tgz", + "integrity": "sha512-Sk4NQd3GFY0WZWCzndwFMPwJhtD0y9qjsQ+pjID0/03nK9pxyBCUoUHCho8QYBLBVhi0ssL8UkNPHqbgSOFPIQ==", "license": "MIT", "engines": { "node": ">=20" @@ -151,18 +151,18 @@ } }, "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", - "content-type": "^2.0.0", + "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", + "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", - "qs": "^6.15.2", + "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, @@ -717,9 +717,9 @@ } }, "node_modules/hono": { - "version": "4.13.13", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz", - "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==", + "version": "4.13.19", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.19.tgz", + "integrity": "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==", "license": "MIT", "engines": { "node": ">=16.9.0" diff --git a/host/server/proxy.mjs b/host/server/proxy.mjs index c2a258192a5c506dd6ee0983b9b6b6538687f744..5a2a7a0b31a5481c2eb32e813b1f033b88299ae9 100644 --- a/host/server/proxy.mjs +++ b/host/server/proxy.mjs @@ -129,7 +129,7 @@ export function sseRewriter(rewrite) { export function proxyHttp( request, response, - { target, path, token, rewrite, ticketCookie }, + { target, path, token, rewrite, ticketCookie, transformHtml }, ) { const transport = target.protocol === "https:" ? https : http; const upstream = transport.request(target, { @@ -152,10 +152,29 @@ export function proxyHttp( const type = String(incoming.headers["content-type"] ?? ""); const json = rewrite && type.includes("application/json"); const sse = rewrite && type.includes("text/event-stream"); - const headers = responseHeaders(incoming.headers, json || sse); + // A small page whose markup changes on the way, such as the web client's computer view. + const html = transformHtml && incoming.statusCode === 200 && type.includes("text/html"); + const headers = responseHeaders(incoming.headers, json || sse || html); if (ticketCookie) headers["set-cookie"] = ticketCookie; if (type.includes("text/event-stream")) headers["x-accel-buffering"] = "no"; - if (json) { + if (html) { + const chunks = []; + let size = 0; + incoming.on("data", (chunk) => { + size += chunk.length; + if (size > 4 * 1024 * 1024) { + incoming.destroy(); + sendJson(response, 502, { error: "Host 响应内容过大" }); + } else chunks.push(chunk); + }); + incoming.on("end", () => { + if (response.headersSent || response.destroyed) return; + const body = Buffer.from(transformHtml(Buffer.concat(chunks).toString("utf8"))); + response.writeHead(200, { ...headers, "content-length": body.length }); + response.end(body); + }); + incoming.on("error", () => sendJson(response, 502, { error: "Host 响应中断" })); + } else if (json) { const chunks = []; let size = 0; incoming.on("data", (chunk) => { diff --git a/host/server/public/app.js b/host/server/public/app.js index 7fd6648b8c17cff6dc22ffb292f30ca08e6d3504..8820b94378a64316cd747de1aff7ed7ee61a5436 100644 --- a/host/server/public/app.js +++ b/host/server/public/app.js @@ -15,6 +15,7 @@ import { createSkillsEditor } from './skills.js'; import { createApps } from './apps.js'; import { createPromptEditor } from './prompts.js'; import { createDevices } from './devices.js'; +import { createWebClientPage } from './web-client.js'; import { createNetworkEditor } from './network.js'; import { createExecutionEditor } from './execution.js'; import { createFederationEditor } from './federation.js'; @@ -22,7 +23,10 @@ import { createWebhookEditor } from './webhooks.js'; import { createSharingEditor } from './sharing.js'; const aliases = { profile: 'general', notifications: 'devices', plugins: 'apps', connectors: 'apps' }; -let initialized = false, state = null, activeView = 'overview', poll = null, toastTimer, statusPending = false; +const sessionPaths = new Set(['/admin/api/session', '/admin/api/login', '/admin/api/setup']); +const expiredSession = () => new Error(t('会话已过期,请重新登录。')); +let initialized = false, state = null, activeView = 'overview', poll = null, toastTimer; +let consoleSession = null, statusPending = null; function toast(message, error = false) { clearTimeout(toastTimer); @@ -33,19 +37,38 @@ function toast(message, error = false) { toastTimer = setTimeout(() => { element.hidden = true; }, 5000); } -async function api(path, { method = 'GET', body } = {}) { +async function api(path, { method = 'GET', body, signal = consoleSession?.signal, binary = false } = {}) { + const session = consoleSession; + const publicPath = sessionPaths.has(path); + if (!publicPath && !session) throw expiredSession(); if (body === undefined && !['GET', 'HEAD'].includes(method)) body = {}; - const response = await fetch(path, { - method, credentials: 'same-origin', - headers: { 'content-type': 'application/json', 'x-grokbot-csrf': '1' }, - ...(body !== undefined ? { body: JSON.stringify(body) } : {}), - }); - const value = await response.text().then(text => (text ? JSON.parse(text) : {})); + let response; + try { + response = await fetch(path, { + method, credentials: 'same-origin', signal, + headers: { 'content-type': 'application/json', 'x-grokbot-csrf': '1' }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + } catch (error) { + if (signal?.aborted) throw error; + throw new Error(t('无法连接管理服务。')); + } + if (response.status === 401 && !publicPath) { + const error = expiredSession(); + if (session === consoleSession) showAuth(error.message); + throw error; + } if (!response.ok) { - if (response.status === 401 && !['/admin/api/login', '/admin/api/setup'].includes(path)) showAuth(); - throw new Error(t(value.error) || t('请求失败 ({0})', response.status)); + const value = await response.json().catch(() => null); + throw new Error(typeof value?.error === 'string' && value.error.trim() ? t(value.error) : t('请求失败 ({0})', response.status)); + } + if (binary) return response.blob(); + if (response.status === 204) return {}; + try { return await response.json(); } + catch (error) { + if (signal?.aborted) throw error; + throw new Error(t('管理服务返回了无效响应 (HTTP {0})。', response.status)); } - return value; } const act = (control, work) => busy(control, async () => { @@ -62,6 +85,7 @@ const views = { overview: createOverview(context), general: createGeneral(context), model: createModelPage(context), speech: createSpeechPage(context), media: createMediaEditor(context), 'web-services': createWebServicesEditor(context), harness: createHarnessEditor(context), skills: createSkillsEditor(context), apps: createApps(context), prompts: createPromptEditor(context), devices: createDevices(context), + 'web-client': createWebClientPage(context), network: createNetworkEditor(context), execution: createExecutionEditor(context), federation: createFederationEditor(context), webhooks: createWebhookEditor(context), sharing: createSharingEditor(context), }; @@ -70,7 +94,9 @@ const loginStage = createLoginStage(); localize(document.body); $('#nav-toggle').innerHTML = icon('menu'); -function showAuth() { +function showAuth(message = '') { + consoleSession?.abort(); consoleSession = null; + statusPending?.abort(); statusPending = null; clearInterval(poll); poll = null; state = null; $('#console').hidden = true; $('#loading').hidden = true; $('#auth-screen').hidden = false; $('#auth-title').textContent = initialized ? t('登录 Host') : t('设置 Host'); @@ -82,17 +108,23 @@ function showAuth() { $('#auth-submit').setAttribute('aria-label', initialized ? t('登录') : t('创建管理员')); $('#auth-password').value = ''; for (const view of Object.values(views)) view.reset?.(); - loginStage.show(); + for (const dialog of all('dialog[open]')) dialog.close(); + loginStage.show(message); + if (message) $('#auth-password').focus(); } async function showConsole() { + const session = consoleSession = new AbortController(); loginStage.hide(); $('#auth-screen').hidden = true; $('#loading').hidden = true; $('#console').hidden = false; $('#auth-form').reset(); + const checking = t('正在检查'); + setHealth(checking, ''); views.overview.statusUnavailable(checking); await refresh(true); + if (session !== consoleSession) return; showView(activeView); clearInterval(poll); - poll = setInterval(() => { if (!document.hidden) refresh().catch(() => {}); }, 5000); + poll = setInterval(() => { if (!document.hidden) refresh(); }, 5000); } function showView(view) { @@ -113,23 +145,49 @@ function showView(view) { function hostTitle() { if (state.host.connected) return state.host.busy ? [t('任务运行中'), 'accent'] : [t('Host 就绪'), 'success']; + if (state.model.configured && state.host.waitingForExecutionNode) return [t('需要执行节点'), 'warn']; return state.model.configured ? [t('等待 Host'), 'warn'] : [t('等待配置'), 'warn']; } +function setHealth(title, tone) { + $('#header-health').textContent = title; + $('#header-health').dataset.tone = tone; +} + +function statusUnavailable(detail) { + state = null; + const title = t('状态不可用'); + setHealth(title, 'warn'); views.overview.statusUnavailable(title, detail); +} + async function refresh(showError = false) { - if (statusPending) return; - statusPending = true; + if (!consoleSession || statusPending) return; + // Only the current probe may update health, even if an old one finishes after re-login. + const request = statusPending = new AbortController(); + const timeout = setTimeout(() => request.abort(new Error(t('读取 Host 状态超时。'))), 12_000); try { - state = await api('/admin/api/status'); - const [title, tone] = hostTitle(); - $('#header-health').textContent = title; - $('#header-health').dataset.tone = tone; + const next = await api('/admin/api/status', { signal: request.signal }); + if (request !== statusPending) return; + state = next; + setHealth(...hostTitle()); for (const view of Object.values(views)) view.status?.(state, view === views[activeView]); } catch (error) { + if (request !== statusPending) return; + statusUnavailable(error.message); if (showError) toast(error.message, true); - } finally { statusPending = false; } + } finally { + clearTimeout(timeout); + if (statusPending === request) statusPending = null; + } } +addEventListener('offline', () => { + if (!consoleSession) return; + statusPending?.abort(); statusPending = null; + statusUnavailable(t('无法连接管理服务。')); +}); +addEventListener('online', () => { if (!document.hidden) refresh(); }); + $('#auth-form').addEventListener('submit', event => { event.preventDefault(); busy($('#auth-submit'), async () => { diff --git a/host/server/public/apps.js b/host/server/public/apps.js index a8fd603c04ee2f069dc52aa1270813b2fcb7a8ac..f05f8dc8a47dec6d42701c9bc47bb19b4e2bd24d 100644 --- a/host/server/public/apps.js +++ b/host/server/public/apps.js @@ -94,7 +94,7 @@ export function createApps(context) { run: trigger => act(trigger, () => run(app, action)) })))); const valid = /^data:image\/(png|jpeg|webp);base64,/.test(app.iconDataUrl || ''); const meta = [app.version, Number.isInteger(app.toolCount) && t('{0} 个工具', app.toolCount), app.skills?.length && t('{0} 个技能', app.skills.length)].filter(Boolean); - const element = item({ image: valid ? app.iconDataUrl : '', tile: icon(builtin ? 'bolt' : 'plug'), title: name, badges, + const element = item({ image: valid ? app.iconDataUrl : '', icon: builtin ? 'bolt' : 'plug', title: name, badges, description: appCopy(app.description), meta: meta.length ? [meta.join(' · ')] : [], actions: controls }); element.classList.add('connector-row'); element.dataset.appId = app.id; const content = element.querySelector('.item-copy'); diff --git a/host/server/public/devices.js b/host/server/public/devices.js index dfa78a6876f1d5a29748528ce02b3088eb9afe73..756b89c26cf1df5cd195205fc9ace1f859814bc5 100644 --- a/host/server/public/devices.js +++ b/host/server/public/devices.js @@ -4,7 +4,7 @@ import { icon } from './icons.js'; import { createPushEditor } from './push.js'; import { createNotifications } from './notifications.js'; -const kinds = { iphone: 'iPhone', ipad: 'iPad', mac: 'Mac', desktop: '电脑', ios: 'iPhone / iPad' }; +const kinds = { iphone: 'iPhone', ipad: 'iPad', mac: 'Mac', windows: 'Windows', android: 'Android', web: '网页版', desktop: '电脑', ios: 'iPhone / iPad' }; const permissions = { authorized: '已允许', granted: '已允许', provisional: '临时允许', ephemeral: '临时允许', denied: '已拒绝', notDetermined: '尚未询问', not_determined: '尚未询问', unknown: '尚未报告' }; @@ -94,7 +94,7 @@ export function createDevices(context) { }) }, ])); } - const row = item({ tile: icon('devices'), title: device.name, badges, meta, actions }); + const row = item({ icon: 'devices', title: device.name, badges, meta, actions }); row.classList.add('device-row'); if (device.revokedAt) row.classList.add('revoked'); row.querySelector('.item-title span').dataset.private = ''; for (const error of [notice.lastError, notice.registrationError].filter(Boolean)) row.querySelector('.item-copy').append(node('p', 'error', error)); diff --git a/host/server/public/federation.js b/host/server/public/federation.js index 46b617f03c319bd79b06825541b29dbfd12bc686..3b7f9538a0a6255507bcef6afe21249add9df872 100644 --- a/host/server/public/federation.js +++ b/host/server/public/federation.js @@ -137,7 +137,7 @@ export function createFederationEditor({ api, toast, act }) { }) }, ]); const local = peer.allowedBots.map(id => roster.find(bot => bot.id === id)?.name ?? id); - const row = item({ tile: icon('swap'), title: peer.name, + const row = item({ icon: 'swap', title: peer.name, badges: [peer.error ? badge(t('同步失败'), 'danger') : !peer.enabled ? badge(t('已停用')) : badge(t('已连接'), 'success')], meta: [`${t('本地 Bot')}:${local.join(' · ') || t('无')}`, `${t('对方 Bot')}:${peer.remoteBots.map(bot => bot.name).join(' · ') || t('无')}`, peer.error || `${t('最近同步')} · ${time(peer.lastSyncAt)}`], @@ -152,7 +152,7 @@ export function createFederationEditor({ api, toast, act }) { const peer = config.peers.find(value => value.id === entry.peerId), outgoing = entry.direction === 'outbound'; const local = roster.find(bot => bot.id === (outgoing ? entry.fromAgentId : entry.toAgentId))?.name ?? t('本地 Bot'); const remote = peer?.remoteBots.find(bot => bot.id === (outgoing ? entry.toAgentId : entry.fromAgentId))?.name ?? t('远程 Bot'); - list.append(item({ tile: icon('swap'), title: outgoing ? `${local} → ${remote}` : `${remote} → ${local}`, + list.append(item({ icon: 'swap', title: outgoing ? `${local} → ${remote}` : `${remote} → ${local}`, meta: [`${peer?.name ?? ''} · ${time(entry.createdAt)}`], actions: [badge(t(states[entry.state] ?? entry.state))] })); } } diff --git a/host/server/public/icons.js b/host/server/public/icons.js index 9b52984962bc13b389cf0542b7ba0ec676c553d1..86d64f76a808868f15e6e3505718af457812bda5 100644 --- a/host/server/public/icons.js +++ b/host/server/public/icons.js @@ -19,6 +19,7 @@ const paths = { share: '', settings: '', plus: '', + archive: '', close: '', copy: '', refresh: '', @@ -36,3 +37,7 @@ export function icon(name, size = 16) { return ``; } +export function isBuiltinIcon(name) { + return Object.hasOwn(paths, name); +} + diff --git a/host/server/public/ids.js b/host/server/public/ids.js new file mode 100644 index 0000000000000000000000000000000000000000..eb63db4e53c2f714a38e9b98bf9683c45f54089f --- /dev/null +++ b/host/server/public/ids.js @@ -0,0 +1,16 @@ +// crypto.randomUUID() is secure-context only. The Host admin page also runs on LAN HTTP. +let sequence = 0; + +export function clientId(prefix = 'item', cryptoImpl = globalThis.crypto) { + try { + const value = cryptoImpl?.randomUUID?.(); + if (typeof value === 'string' && value) return `${prefix}-${value.slice(0, 8)}`; + } catch {} + try { + const values = new Uint32Array(2); + cryptoImpl?.getRandomValues?.(values); + if (values[0] || values[1]) return `${prefix}-${values[0].toString(36)}${values[1].toString(36)}`; + } catch {} + sequence += 1; + return `${prefix}-${Date.now().toString(36)}${sequence.toString(36)}`; +} diff --git a/host/server/public/index.html b/host/server/public/index.html index 19f819440ba9c3a62b6e43cf2522d4524ccde527..5f49a1e8d181a910f7020c2522a3cc4ffa9d43e5 100644 --- a/host/server/public/index.html +++ b/host/server/public/index.html @@ -60,6 +60,7 @@ + diff --git a/host/server/public/locales-en.js b/host/server/public/locales-en.js index 7625a7226271d8c97f3043e40e93a56d396ed3a3..7b19840433bea4427249fe3cda90d15d7918ff20 100644 --- a/host/server/public/locales-en.js +++ b/host/server/public/locales-en.js @@ -1,4 +1,6 @@ export default { + '需要执行节点': 'Execution node required', '配置执行节点': 'Set up a node', '配置节点': 'Set up node', + '分机部署需要连接独立的执行电脑,Bot 才能开始聊天。': 'Connect the separate execution computer before starting a chat in a split deployment.', '通知偏好': 'Notification preferences', '通知频率': 'Notification frequency', '适用于手机和 Mac;授权与提问仍会提醒。': 'Applies to mobile and Mac. Approvals and questions still notify you.', @@ -58,7 +60,7 @@ export default { 'Agent 能力': 'Agent Capabilities', '上下文容量': 'Context Capacity', '摘要阈值': 'Summary Threshold', - '支持 1M、400K。留空或 0:容量未知,摘要阈值沿用原策略。': 'Accepts 1M or 400K. Blank or 0: unknown capacity, original summary policy.', + '支持 1M、400K。同步后会自动填入上下文容量和摘要阈值。': 'Supports 1M and 400K. Syncing automatically fills the context capacity and summary threshold.', '请输入 0–100M 的整数 Token 数,如 1M、400K。': 'Enter a whole token count from 0 to 100M, such as 1M or 400K.', '摘要阈值必须小于上下文容量。': 'The summary threshold must be below the context capacity.', '请检查上下文设置。': 'Check the context settings.', @@ -136,6 +138,11 @@ export default { "连接应用": "Connected Apps", "通知中心": "Notification Center", "请求失败 ({0})": "Request failed ({0})", + "会话已过期,请重新登录。": "Session expired. Sign in again.", + "无法连接管理服务。": "Cannot reach the admin service.", + "管理服务返回了无效响应 (HTTP {0})。": "Invalid response from the admin service (HTTP {0}).", + "状态不可用": "Status unavailable", + "读取 Host 状态超时。": "Host status request timed out.", "登录管理页面": "Sign in to Admin", "设置你的 Host": "Set Up Your Host", "创建管理员密码": "Create Admin Password", @@ -334,6 +341,7 @@ export default { "困难任务": "Hard tasks", "模型默认": "Model default", "Jev 决定": "Jev decides", + "极低": "Minimal", "轻度": "Light", "中度": "Moderate", "高度": "High", @@ -382,6 +390,9 @@ export default { "正在读取用户资料…": "Loading user profile…", "模型服务": "Model service", "获取模型": "Fetch models", + "同步模型": "Sync models", + "从同步列表选择模型": "Select a synced model", + "已同步 {0} 个模型": "Synced {0} models", "默认模型": "Default model", "智能路由": "Smart routing", "Jev 分类器": "Jev classifier", @@ -556,6 +567,10 @@ export default { "还没有模型": "No models yet", "添加模型后选择默认模型。": "Add models, then choose the defaults.", "兼容 OpenAI 的接口地址": "OpenAI-compatible endpoint", + "接口格式": "API format", + "OpenAI 兼容或 Anthropic Messages": "OpenAI-compatible or Anthropic Messages", + "与服务商提供的接口一致": "Match the API your provider offers", + "模型服务的接口地址": "Model service endpoint", "按任务难度选择模型和思考强度": "Chooses the model and effort by task difficulty", "保存后启动 Host": "Save to start the Host", "配置应用失败,请检查 Host 日志": "Could not apply the configuration. Check the Host logs.", @@ -667,8 +682,8 @@ export default { "签名密钥只显示这一次,请立即保存。": "The signing key is shown only once. Save it now.", "选择文件": "Choose file", "Host 就绪": "Host ready", - "还没有对话模型": "No chat model yet", - "填写兼容 OpenAI 的接口后,Host 才会启动。": "The Host starts once an OpenAI-compatible endpoint is set.", + "还没有对话模型": "No model configured yet", + "配置 OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages 接口后,Host 才会启动。": "Set up an OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages endpoint to start the Host.", "配置模型": "Set up model", "还没有配对设备": "No paired devices yet", "用配对码连接电脑或手机客户端。": "Connect a desktop or phone client with a pairing code.", @@ -679,9 +694,135 @@ export default { "初始化密钥,见数据目录中的 setup-key 文件": "Setup key from the setup-key file in the data directory", "正在工作": "Working", "今天 {0} Token,{1} 次请求": "{0} tokens, {1} requests today", - "配置对话模型": "Set up a chat model", + "配置对话模型": "Set up a model", "后启动 Host": "to start the Host", "启动": "to start", "{0} 个 Bot": "{0} Bots", "{0} 个 Bot 待命": "{0} Bots standing by", + "对话模型": "Chat model", + "模型档案": "Model profiles", + "Bot 路由": "Bot routes", + "模型路由记录": "Model routing log", + "刷新 Bot": "Refresh Bots", + "当前是旧版单模型配置。保存后会转成服务和档案的格式,模型、API Key 和思考强度不变。": "This Host still uses the legacy single-model configuration. Saving converts it to services and profiles; the model, API key and thinking effort stay the same.", + "检测到旧版模型配置。请在模型页确认迁移后再保存。": "Legacy model configuration detected. Confirm the migration on the model page, then save.", + "当前仍使用旧版按任务难度路由(Jev)。保存后会迁移为按 Bot 路由,并移除智能路由界面;如需保留旧配置,请不要保存。": "This Host still uses legacy task-difficulty routing (Jev). Saving migrates it to per-Bot routing and removes the smart-routing interface. Do not save if you need to keep the legacy configuration.", + "迁移旧版模型路由?": "Migrate the legacy model routing?", + "保存后会改为按 Bot 选择模型,旧版按任务难度路由和 Jev 选择将不再生效。": "Saving switches to per-Bot model selection. Legacy task-difficulty routing and Jev selection will stop applying.", + "迁移并保存": "Migrate and save", + "默认服务": "Default service", + "添加模型服务": "Add model service", + "添加模型档案": "Add model profile", + "编辑模型服务": "Edit model service", + "编辑模型档案": "Edit model profile", + "{0} 个模型档案": "{0} model profiles", + "还没有模型服务": "No model services yet", + "还没有模型档案": "No model profiles yet", + "尚未创建模型档案": "No model profiles yet", + "添加一个模型服务后,再创建模型档案。": "Add a model service, then create a model profile.", + "每个档案绑定一个服务、模型和可用思考强度。": "Each profile binds a service, model, and available reasoning efforts.", + "可用思考强度": "Available reasoning efforts", + "仅模型默认": "Model default only", + "上下文 {0} · 摘要 {1}": "Context {0} · summary {1}", + "默认路由": "Default route", + "还没有可路由的模型": "No routable models yet", + "添加模型档案后,设置所有 Bot 的默认模型。": "After adding a model profile, choose the default model for all Bots.", + "主模型": "Primary model", + "备用模型": "Backup model", + "备用模型 {0}": "Backup model {0}", + "添加备用模型": "Add backup model", + "移除备用模型": "Remove backup model", + "仅在主模型未输出任何内容时,才会按顺序尝试备用模型。": "Backups are tried in order only when the primary model has not produced any output.", + "先设置默认路由": "Set a default route first", + "模型档案准备好后,才可为单个 Bot 覆盖路由。": "Once model profiles are ready, individual Bots can override the route.", + "Host 未连接或尚无 Bot": "Host is not connected or has no Bots yet", + "Host 连接后会在这里显示可覆盖的 Bot。": "Bots that can override the route appear here after the Host connects.", + "编辑 Bot 路由": "Edit Bot route", + "压缩上下文": "Summarize context", + "压缩“{0}”的上下文?": "Summarize the context for \"{0}\"?", + "将使用此 Bot 当前路由的模型生成摘要。原始对话会保留,并会消耗模型 Token。": "Uses this Bot's current route to generate a summary. The original conversation is retained and model tokens are used.", + "开始压缩": "Summarize now", + "上下文已压缩": "Context summarized", + "Bot 正在运行,请在任务结束后再压缩": "Bot is running. Wait for the task to finish before summarizing.", + "暂不支持压缩群组 Bot": "Group Bot summarization is not supported yet.", + "当前 Host 版本不支持手动压缩": "This Host version does not support manual summarization.", + "上下文压缩被中断,请稍后重试": "Context summarization was interrupted. Try again shortly.", + "使用默认": "Use default", + "使用默认路由": "Use default route", + "已覆盖": "Overridden", + "当前 Host 未报告此 Bot;保存时会保留其路由。": "The current Host did not report this Bot; its route will be retained when saved.", + "已配置": "Configured", + "缺少 API Key": "API key missing", + "请先添加模型服务。": "Add a model service first.", + "请先添加模型档案。": "Add a model profile first.", + "请设置默认路由。": "Set a default route.", + "请填写“{0}”的 API Key。": "Enter the API key for \"{0}\".", + "请先选择模型服务。": "Choose a model service first.", + "请先移除或改用引用此服务的模型档案。": "Remove or reassign the model profiles that use this service first.", + "请先从 {0} 移除此档案。": "Remove this profile from {0} first.", + "失败类别": "Failure class", + "会话": "Session", + "暂无路由记录": "No routing records yet", + "模型回退": "Model fallback", + "没有可用备用模型": "No usable backup model", + "未选择": "not selected", + "跳过同 API Key 的模型": "Skipped models with the same API key", + "网页版": "Web client", + "在此浏览器打开": "Open in this browser", + "访问": "Access", + "启用网页版": "Enable the web client", + "在任何设备的浏览器里使用 Bot,不用安装客户端;只能使用 Host 上的 Bot 电脑": "Use your Bots from a browser on any device without installing a client; only the Bot computer on the Host is available", + "界面包": "Interface bundle", + "未上传": "Not uploaded", + "网页地址": "Web address", + "在其他设备打开,输入「设备与通知」里创建的配对码登录": "Open it on another device and sign in with a pairing code from Devices & Notifications", + "复制网页地址": "Copy web address", + "当前 Host 地址是 http。网页版可以使用,但语音输入、麦克风和浏览器通知需要 https;在公网使用时请配置 https。": "This Host address uses http. The web client works, but dictation, the microphone and browser notifications need https; set up https before using it over the internet.", + "上传界面包": "Upload a bundle", + "在电脑上运行 node web/patchers/patch.mjs,生成 web/output/GrokBotLocal-web-1.1.0.zip 后上传。界面取自你自己下载的官方 Windows 安装包,只保存在这台 Host 上,未登录的访问者拿不到。": "Run node web/patchers/patch.mjs on a computer, then upload the resulting web/output/GrokBotLocal-web-1.1.0.zip. The interface comes from your own download of the official Windows installer, stays on this Host and is never served to visitors who have not signed in.", + "选择文件并上传": "Choose a file and upload", + "删除界面包": "Delete the bundle", + "网页版随之停用;已登录的浏览器仍列在「设备与通知」里,可在那里撤销": "The web client stops; signed-in browsers stay under Devices & Notifications, where you can revoke them", + "界面 {0} · {1} 个文件 · {2} MB · 上传于 {3}": "Interface {0} · {1} files · {2} MB · uploaded {3}", + "正在上传 {0}%": "Uploading {0}%", + "网页版界面包已安装": "Web client bundle installed", + "网页版已启用": "Web client enabled", + "网页版已停用": "Web client disabled", + "删除网页版界面包?": "Delete the web client bundle?", + "网页版会停用。之后要使用,需要重新上传界面包。": "The web client will stop. To use it again, upload a bundle again.", + "网页版界面包已删除": "Web client bundle deleted", + "浏览器": "Browser", + "登录网页版": "Sign in to the web client", + "在 Host 管理页「设备与通知」创建 6 位配对码,输入后即可在这个浏览器里使用你的 Bot。": "Create a six-character pairing code under Devices & Notifications on the Host admin page, then enter it to use your Bots in this browser.", + "6 位配对码": "Six-character pairing code", + "进入网页版": "Open the web client", + "这个地址没有加密(http)。网页版可以用,但语音输入、麦克风和浏览器通知需要 https 地址;在公网使用时请配置 https。": "This address is not encrypted (http). The web client works, but dictation, the microphone and browser notifications need an https address; set up https before using it over the internet.", + "请输入 6 位配对码。": "Enter the six-character pairing code.", + "已登录": "Signed in", + "这个浏览器已登录为“{0}”。": "This browser is signed in as “{0}”.", + "网页版还没有启用。请管理员在 Host 管理页「网页版」上传界面包并启用。": "The web client is not enabled yet. On the Host admin page, open Web client, upload a bundle and enable it.", + "登录已失效,请输入新的配对码。": "Your sign-in has expired. Enter a new pairing code.", + "无法连接 Host:{0}": "Cannot reach the Host: {0}", + "设备名称需要 1–80 个字符": "Device names need 1–80 characters", + "网页版未启用": "The web client is not enabled", + "请从网页版登录页操作": "Use the web client sign-in page", + "请从网页版发起请求": "Send this request from the web client", + "请先登录网页版": "Sign in to the web client first", + "请先上传并启用网页版": "Upload and enable the web client first", + "请先上传网页版界面包": "Upload a web client bundle first", + "请上传 ZIP 格式的网页版界面包": "Upload the web client bundle as a ZIP file", + "网页版界面包过大": "The web client bundle is too large", + "网页版界面包大小无效": "The web client bundle has an invalid size", + "不是网页版界面包(ZIP 目录无效)": "Not a web client bundle (invalid ZIP directory)", + "网页版界面包目录无效": "The web client bundle has an invalid directory", + "网页版界面包条目无效": "The web client bundle has an invalid entry", + "网页版界面包含不支持的条目": "The web client bundle has an unsupported entry", + "网页版界面包条目位置无效": "The web client bundle has an entry at an invalid position", + "缺少 web-bundle.json,请用 web/patchers/patch.mjs 生成网页版界面包": "web-bundle.json is missing; build the bundle with web/patchers/patch.mjs", + "web-bundle.json 格式错误": "web-bundle.json is malformed", + "网页版界面包格式不受支持,请用同一版本的工具重新生成": "Unsupported bundle format; build it again with the tools from the same release", + "网页版界面包的版本无效": "The web client bundle has an invalid version", + "web-bundle.json 缺少文件清单": "web-bundle.json has no file list", + "网页版界面包的文件与清单不一致": "The files of the web client bundle do not match its list", + "启用状态无效": "Invalid enabled state", }; diff --git a/host/server/public/login.js b/host/server/public/login.js index 027742977bd5b9f144afd6c0109ac9e70e5d7d7f..2cc6c973dd2212721f8688d380288f4ceb0cb4ef 100644 --- a/host/server/public/login.js +++ b/host/server/public/login.js @@ -32,7 +32,7 @@ export function createLoginStage() { for (const type of ['focus', 'blur', 'input']) password.addEventListener(type, follow); password.addEventListener('input', () => { if (!message.hidden) say(); }); return { - show() { say(); stopBlink(); stopBlink = blink(() => [face]); follow(); }, + show(message) { say(message); stopBlink(); stopBlink = blink(() => [face]); follow(); }, hide() { stopBlink(); }, thinking() { form.classList.add('pending'); state('up'); }, async error(text) { diff --git a/host/server/public/media-editor-ui.js b/host/server/public/media-editor-ui.js index 799844c2ca0c067f51822096643b1727a03e2989..41f3ea8ab8ecec7b53943319fe74abcef35b66fc 100644 --- a/host/server/public/media-editor-ui.js +++ b/host/server/public/media-editor-ui.js @@ -1,5 +1,6 @@ import { t } from './i18n.js'; import { node, iconButton, item, toggle, menu, confirmAction } from './ui.js'; +import { clientId } from './ids.js'; // Shared building blocks for the media and web tool pages: provider lists, editor dialogs and form fields. export const labels = { image: '图片生成', video: '视频生成', watchVideo: '视频理解', videoReview: '视频审核' }; @@ -55,7 +56,7 @@ export function sectionHead(title, addLabel, onAdd) { export const modelOptions = (config, kind) => [['', t('停用')], ...config.models.filter(entry => entry.kind === kind && entry.enabled && config.providers.find(provider => provider.id === entry.providerId)?.enabled).map(entry => [entry.id, entry.name])]; -export const uid = () => `service-${crypto.randomUUID().slice(0, 8)}`; +export const uid = () => clientId('service'); export function providerDialog(panel, { adapters, save, act }) { const { dialog, form, body, submit } = modal(panel, '供应商'); diff --git a/host/server/public/model.js b/host/server/public/model.js index d4729c8c658a6a12ace23dcb53fbcb4153ca312a..dab074251967275b1bdbf4cbf63ea766fd7b3444 100644 --- a/host/server/public/model.js +++ b/host/server/public/model.js @@ -1,236 +1,466 @@ import { t, html } from './i18n.js'; -import { $, node } from './ui.js'; -import { icon } from './icons.js'; +import { $, node, item, badge, empty, iconButton, menu, confirmAction } from './ui.js'; import { createRoutingLog } from './routing-log.js'; +import { clientId } from './ids.js'; -const tiers = [['routine', '一般任务'], ['reasoning', '中等任务'], ['expert', '困难任务']]; -const levels = ['none', 'low', 'medium', 'high', 'xhigh', 'max']; -const levelLabels = { default: '模型默认', auto: 'Jev 决定', none: '无', low: '轻度', medium: '中度', high: '高度', xhigh: '超高', max: '最高' }; -const choices = (select, values, chosen) => { +const formats = [ + ['openai', 'OpenAI Chat Completions'], + ['openai-responses', 'OpenAI Responses'], + ['anthropic', 'Anthropic Messages'], +]; +const levels = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']; +const levelLabels = { default: '模型默认', none: '无', minimal: '极低', low: '轻度', medium: '中度', high: '高度', xhigh: '超高', max: '最高' }; +const defaultUrls = { openai: 'https://api.openai.com/v1', 'openai-responses': 'https://api.openai.com/v1', anthropic: 'https://api.anthropic.com' }; +const defaultContextWindowTokens = 0, defaultSummaryThresholdTokens = 0; + +const clone = value => structuredClone(value); +const uid = prefix => clientId(prefix); +const choice = (select, values, selected) => { select.replaceChildren(...values.map(([value, label]) => new Option(t(label), value))); - select.value = values.some(([value]) => value === chosen) ? chosen : values[0]?.[0] ?? ''; + select.value = values.some(([value]) => value === selected) ? selected : values[0]?.[0] ?? ''; }; -const row = (title, hint, control) => ``; - -function parseTokenCount(text) { - if (!text.trim()) return 0; - const match = text.trim().match(/^(\d+(?:\.\d*)?|\.\d+)\s*([km]?)$/i); +const parseTokenCount = value => { + const source = String(value ?? '').trim(); + if (!source) return 0; + const match = source.match(/^(\d+(?:\.\d*)?|\.\d+)\s*([km]?)$/i); if (!match) return NaN; const precision = { '': 0, k: 3, m: 6 }[match[2].toLowerCase()]; const [whole, decimals = ''] = match[1].split('.'); const fraction = decimals.replace(/0+$/, ''); if (fraction.length > precision) return NaN; - const value = Number((whole || '0') + fraction.padEnd(precision, '0')); - return Number.isSafeInteger(value) && value <= 100_000_000 ? value : NaN; -} - -function formatTokenCount(value) { + const number = Number((whole || '0') + fraction.padEnd(precision, '0')); + return Number.isSafeInteger(number) && number <= 100_000_000 ? number : NaN; +}; +const formatTokenCount = value => { if (!value) return ''; if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(6).replace(/\.?0+$/, '')}M`; if (value >= 1_000) return `${(value / 1_000).toFixed(3).replace(/\.?0+$/, '')}K`; return String(value); +}; +const emptyRouting = () => ({ version: 1, providers: [], profiles: [], defaultRoute: null, botRoutes: {} }); + +function editor(panel, id) { + const dialog = node('dialog', 'dialog wide'); + dialog.id = id; + const form = document.createElement('form'); + const head = node('div', 'dialog-head'), title = node('h2'), body = node('div', 'dialog-body'), foot = node('div', 'dialog-foot'); + const cancel = node('button', 'btn', t('取消')); cancel.type = 'button'; cancel.onclick = () => dialog.close(); + const submit = node('button', 'btn btn-primary', t('保存')); submit.type = 'submit'; + head.append(title, iconButton('close', t('关闭'), () => dialog.close())); + foot.append(cancel, submit); form.append(head, body, foot); dialog.append(form); panel.append(dialog); + return { dialog, form, title, body, submit }; +} + +function formField(parent, name, label, type = 'text') { + const field = node('label', 'field', t(label)); + const input = document.createElement(type === 'textarea' ? 'textarea' : 'input'); + if (type !== 'textarea') input.type = type; + input.name = name; + if (type === 'password') { input.autocomplete = 'new-password'; input.dataset.private = ''; } + if (type === 'url') { input.spellcheck = false; input.dataset.private = ''; } + field.append(input); parent.append(field); + return input; +} + +function formSelect(parent, name, label) { + const field = node('label', 'field', t(label)), select = document.createElement('select'); + select.name = name; field.append(select); parent.append(field); return select; } export function createModelPage({ api, toast, busy, refresh }) { const panel = $('[data-panel=model]'); panel.innerHTML = html(`
-

服务

- ${row('Base URL', '兼容 OpenAI 的接口地址', '')} - ${row('API Key', '', '')} -
模型列表从服务读取可用模型
-
-

默认

- ${row('默认模型', '', '')} - -
-

智能路由

- ${row('Jev 分类器', '按任务难度选择模型和思考强度', '')} - -
-

模型能力

-
思考强度与上下文 -
-
-

支持 1M、400K。留空或 0:容量未知,摘要阈值沿用原策略。

-
-
+

模型服务

+

模型档案

+

默认路由

+

Bot 路由

+ -
+
- `); - const form = $('#model-form'), routingLog = createRoutingLog({ api }); - let models = [], policy, loaded = false, active = false; +

模型路由记录

`); + const form = $('#model-form'), providersRoot = $('#model-providers'), profilesRoot = $('#model-profiles'); + const defaultRoot = $('#model-default-route'), botsRoot = $('#model-bot-routes'), routingLog = createRoutingLog({ api }); + const providerEditor = editor(panel, 'model-provider-editor'), profileEditor = editor(panel, 'model-profile-editor'); + const botEditor = editor(panel, 'model-bot-route-editor'); + let config = emptyRouting(), pendingKeys = new Map(), loaded = false, dirty = false, active = false, agents = [], + agentSignature = '', legacyRouting = false, legacyAdaptive = false; - function efforts(select, model, selected, auto = false) { - choices(select, [[auto ? 'auto' : 'default', auto ? 'Jev 决定' : '模型默认'], - ...(models.find(item => item.id === model)?.efforts ?? []).map(value => [value, levelLabels[value]])], selected); - } - function mode() { - const adaptive = $('#adaptive-mode').checked; - $('#manual-effort-row').hidden = adaptive; - $('#adaptive-settings').hidden = !adaptive; - $('#routing-section').hidden = !adaptive; - } - function renderRoutes() { - const root = $('#model-routes'); root.replaceChildren(); - for (const [tier, label] of tiers) { - const line = node('div', 'row'), copy = node('span', 'row-copy'), control = node('span', 'row-control wide'); - copy.append(node('span', 'row-title', t(label))); - const model = document.createElement('select'), effort = document.createElement('select'); - model.dataset.routeModel = tier; effort.dataset.routeEffort = tier; - model.setAttribute('aria-label', `${t(label)} · ${t('模型')}`); - effort.setAttribute('aria-label', `${t(label)} · ${t('思考强度')}`); - choices(model, models.map(item => [item.id, item.id]), policy.routes[tier]?.model); - efforts(effort, model.value, policy.routes[tier]?.effort ?? 'auto', true); - model.addEventListener('change', () => efforts(effort, model.value, 'auto', true)); - control.append(model, effort); line.append(copy, control); root.append(line); + function profileById(id) { return config.profiles.find(profile => profile.id === id); } + function providerById(id) { return config.providers.find(provider => provider.id === id); } + function profileLabel(profile) { + const provider = providerById(profile.providerId); + return `${profile.name} · ${profile.model}${provider ? ` · ${provider.name}` : ''}`; + } + function providerHasKey(provider) { return Boolean(pendingKeys.get(provider.id) || provider.hasApiKey); } + function effortFor(profile, value) { return profile?.efforts?.includes(value) ? value : 'default'; } + function routeCopy(route) { + const primary = profileById(route?.profileId) ?? config.profiles[0]; + if (!primary) return null; + const seen = new Set([primary.id]); + const fallbacks = []; + for (const item of route?.fallbacks ?? []) { + const profile = profileById(item.profileId); + if (!profile || seen.has(profile.id)) continue; + seen.add(profile.id); fallbacks.push({ profileId: profile.id, effort: effortFor(profile, item.effort) }); } + return { profileId: primary.id, effort: effortFor(primary, route?.effort), fallbacks }; } - const captureRoutes = () => Object.fromEntries(tiers.map(([tier]) => [tier, { - model: $(`[data-route-model="${tier}"]`).value, effort: $(`[data-route-effort="${tier}"]`).value }])); - function renderCapabilities() { - const root = $('#model-capabilities'); root.replaceChildren(); - for (const entry of models) { - const line = node('div', 'row stack capability'), chips = node('div', 'chips'); - line.append(node('span', 'row-title mono', entry.id)); - for (const level of levels) { - const chip = node('label', 'chip'), check = document.createElement('input'); - check.type = 'checkbox'; check.checked = entry.efforts.includes(level); - check.setAttribute('aria-label', `${entry.id} · ${t(levelLabels[level])}`); - check.addEventListener('change', () => { - policy.routes = captureRoutes(); - entry.efforts = levels.filter(value => value === level ? check.checked : entry.efforts.includes(value)); - efforts(form.elements.effort, form.elements.model.value, form.elements.effort.value); - renderRoutes(); - }); - chip.append(check, node('span', '', t(levelLabels[level]))); chips.append(chip); - } - const numbers = node('div', 'field-grid'), fields = {}; - const validate = () => { - const values = Object.fromEntries(Object.entries(fields).map(([key, input]) => [key, parseTokenCount(input.value)])); - for (const [key, input] of Object.entries(fields)) { - input.setCustomValidity(Number.isNaN(values[key]) ? t('请输入 0–100M 的整数 Token 数,如 1M、400K。') : ''); - if (Number.isFinite(values[key])) entry[key] = values[key]; - } - const { contextWindowTokens: capacity, summaryThresholdTokens: threshold } = values; - if (Number.isFinite(capacity) && Number.isFinite(threshold) && threshold && threshold >= capacity) - fields.summaryThresholdTokens.setCustomValidity(t('摘要阈值必须小于上下文容量。')); + function routeDescription(route) { + const current = routeCopy(route); + if (!current) return t('尚未配置'); + const primary = profileById(current.profileId); + const fallback = current.fallbacks.map(item => profileById(item.profileId)?.name).filter(Boolean); + return `${primary?.name ?? current.profileId} · ${t(levelLabels[current.effort] ?? current.effort)}${fallback.length ? ` → ${fallback.join(' → ')}` : ''}`; + } + function markDirty() { + dirty = true; + $('#model-apply-title').textContent = t('有未保存的修改'); + } + function applyText(value) { + if (!value?.configured) return t('保存后启动 Host'); + return t({ applied: '配置已应用', waiting: '任务结束后应用', pending: '任务结束后应用', error: '配置应用失败,请检查 Host 日志' }[value.reload?.status] ?? '配置已保存'); + } + function serializedProvider(provider) { + return { id: provider.id, name: provider.name, apiFormat: provider.apiFormat, baseUrl: provider.baseUrl, + apiKey: pendingKeys.get(provider.id) ?? '' }; + } + function input() { + if (!config.providers.length) throw new Error(t('请先添加模型服务。')); + if (!config.profiles.length) throw new Error(t('请先添加模型档案。')); + if (!config.defaultRoute) throw new Error(t('请设置默认路由。')); + for (const provider of config.providers) if (!providerHasKey(provider)) + throw new Error(t('请填写“{0}”的 API Key。', provider.name)); + return { version: 1, ...(legacyRouting ? { migrateLegacyRouting: true } : {}), providers: config.providers.map(serializedProvider), profiles: config.profiles.map(profile => ({ + id: profile.id, name: profile.name, providerId: profile.providerId, model: profile.model, efforts: [...profile.efforts], + contextWindowTokens: profile.contextWindowTokens ?? 0, summaryThresholdTokens: profile.summaryThresholdTokens ?? 0, + })), defaultRoute: routeCopy(config.defaultRoute), botRoutes: Object.fromEntries(Object.entries(config.botRoutes) + .map(([id, route]) => [id, routeCopy(route)]).filter(([, route]) => route)) }; + } + function setConfig(value) { + legacyRouting = value.routingMigrated === true; + // Only an adaptive policy used task-difficulty routing; a single model converts without loss. + legacyAdaptive = legacyRouting && value.legacyAdaptiveRouting === true; + config = { version: 1, providers: (value.providers ?? []).map(provider => ({ ...provider })), + profiles: (value.profiles ?? []).map(profile => ({ ...profile, efforts: [...(profile.efforts ?? [])] })), + defaultRoute: null, botRoutes: clone(value.botRoutes ?? {}) }; + config.defaultRoute = value.defaultRoute ? routeCopy(value.defaultRoute) : null; + config.botRoutes = Object.fromEntries(Object.entries(config.botRoutes) + .map(([id, route]) => [id, routeCopy(route)]).filter(([, route]) => route)); + pendingKeys = new Map(); dirty = false; loaded = true; render(); + const notice = $('#legacy-routing-notice'); + notice.hidden = !legacyRouting; + notice.textContent = !legacyRouting ? '' : legacyAdaptive + ? t('当前仍使用旧版按任务难度路由(Jev)。保存后会迁移为按 Bot 路由,并移除智能路由界面;如需保留旧配置,请不要保存。') + : t('当前是旧版单模型配置。保存后会转成服务和档案的格式,模型、API Key 和思考强度不变。'); + $('#model-apply-title').textContent = applyText(value); + } + function providerOptions(select, selected) { + choice(select, config.providers.map(provider => [provider.id, provider.name]), selected); + } + function profileOptions(select, selected, excluded = new Set()) { + choice(select, config.profiles.filter(profile => !excluded.has(profile.id)).map(profile => [profile.id, profileLabel(profile)]), selected); + } + function effortOptions(select, profileId, selected) { + const profile = profileById(profileId); + choice(select, [['default', '模型默认'], ...(profile?.efforts ?? []).map(level => [level, levelLabels[level]])], effortFor(profile, selected)); + } + function routeEditor(root, route, onChange) { + const current = routeCopy(route); + if (!current) return; + const update = next => onChange(routeCopy(next)); + const primary = node('div', 'row'), primaryCopy = node('span', 'row-copy'), primaryControl = node('span', 'row-control wide'); + primaryCopy.append(node('span', 'row-title', t('主模型'))); + const primaryProfile = document.createElement('select'), primaryEffort = document.createElement('select'); + primaryProfile.setAttribute('aria-label', t('主模型')); primaryEffort.setAttribute('aria-label', t('思考强度')); + profileOptions(primaryProfile, current.profileId); effortOptions(primaryEffort, current.profileId, current.effort); + primaryProfile.onchange = () => { + const nextProfile = profileById(primaryProfile.value); + update({ ...current, profileId: primaryProfile.value, effort: effortFor(nextProfile, current.effort), + fallbacks: current.fallbacks.filter(item => item.profileId !== primaryProfile.value) }); + }; + primaryEffort.onchange = () => update({ ...current, effort: primaryEffort.value }); + primaryControl.append(primaryProfile, primaryEffort); primary.append(primaryCopy, primaryControl); root.append(primary); + current.fallbacks.forEach((fallback, index) => { + const line = node('div', 'row'), copy = node('span', 'row-copy'), control = node('span', 'row-control wide'); + copy.append(node('span', 'row-title', t('备用模型 {0}', index + 1))); + const excluded = new Set([current.profileId, ...current.fallbacks.filter((_, itemIndex) => itemIndex !== index).map(item => item.profileId)]); + const profile = document.createElement('select'), effort = document.createElement('select'); + profile.setAttribute('aria-label', t('备用模型 {0}', index + 1)); effort.setAttribute('aria-label', t('思考强度')); + profileOptions(profile, fallback.profileId, excluded); effortOptions(effort, fallback.profileId, fallback.effort); + profile.onchange = () => { + const next = clone(current); next.fallbacks[index].profileId = profile.value; + next.fallbacks[index].effort = effortFor(profileById(profile.value), fallback.effort); update(next); }; - for (const [key, title] of [['contextWindowTokens', '上下文容量'], ['summaryThresholdTokens', '摘要阈值']]) { - const label = node('label', 'field', t(title)), input = document.createElement('input'); - input.type = 'text'; input.spellcheck = false; input.autocomplete = 'off'; - input.placeholder = t(key === 'contextWindowTokens' ? '未知' : '原策略'); - input.value = formatTokenCount(entry[key]); input.setAttribute('aria-label', `${entry.id} · ${t(title)}`); - fields[key] = input; - input.addEventListener('input', validate); - input.addEventListener('blur', () => { - const value = parseTokenCount(input.value); - if (Number.isFinite(value)) input.value = formatTokenCount(value); - }); - label.append(input); numbers.append(label); - } - validate(); - line.append(chips, numbers); root.append(line); + effort.onchange = () => { const next = clone(current); next.fallbacks[index].effort = effort.value; update(next); }; + const remove = iconButton('close', t('移除备用模型')); + remove.onclick = () => { const next = clone(current); next.fallbacks.splice(index, 1); update(next); }; + control.append(profile, effort, remove); line.append(copy, control); root.append(line); + }); + const used = new Set([current.profileId, ...current.fallbacks.map(item => item.profileId)]); + const nextProfile = config.profiles.find(profile => !used.has(profile.id)); + const add = iconButton('plus', t('添加备用模型')); + add.disabled = !nextProfile; + add.onclick = () => update({ ...current, fallbacks: [...current.fallbacks, { profileId: nextProfile.id, effort: 'default' }] }); + const actions = node('div', 'actions'); actions.append(add); root.append(actions); + } + function renderProviders() { + providersRoot.replaceChildren(); + if (!config.providers.length) { + providersRoot.append(empty(t('还没有模型服务'), t('添加一个模型服务后,再创建模型档案。'))); + return; + } + for (const provider of config.providers) { + const linked = config.profiles.filter(profile => profile.providerId === provider.id); + const more = menu(t('{0} 的更多操作', provider.name), [ + { label: t('编辑'), run: () => showProvider(provider) }, + { label: t('删除'), danger: true, disabled: linked.length > 0, run: trigger => busy(trigger, async () => { + if (!await confirmAction({ title: t('删除“{0}”?', provider.name), message: t('请先移除或改用引用此服务的模型档案。'), action: t('删除') })) return; + config.providers = config.providers.filter(item => item.id !== provider.id); pendingKeys.delete(provider.id); markDirty(); render(); + }) }, + ]); + providersRoot.append(item({ icon: 'model', title: provider.name, + badges: [badge(provider.apiFormat), badge(providerHasKey(provider) ? t('已配置') : t('缺少 API Key'), providerHasKey(provider) ? 'success' : 'danger')], + meta: [provider.baseUrl, linked.length ? t('{0} 个模型档案', linked.length) : t('尚未创建模型档案')], actions: [more] })); } } - function render(config) { - policy = structuredClone(config.policy); models = policy.models; - form.elements.baseUrl.value = config.baseUrl; - const primary = models.find(entry => entry.id === config.model); - if (primary && primary.contextWindowTokens === undefined) primary.contextWindowTokens = config.contextWindowTokens ?? 0; - choices(form.elements.model, models.map(item => [item.id, item.id]), config.model); - efforts(form.elements.effort, config.model, policy.effort); - $('#adaptive-mode').checked = policy.mode === 'adaptive'; - form.elements.classifierModel.value = policy.classifierModel; - form.elements.jevApiKey.placeholder = config.hasJevApiKey ? t('已保存,留空保留') : 'Jev API Key'; - renderRoutes(); renderCapabilities(); mode(); + async function testProfile(profile) { + const result = await api('/admin/api/model/test', { method: 'POST', body: { ...input(), profileId: profile.id } }); + toast(result.message); } - function input() { - if (!form.reportValidity()) throw new Error(t('请检查上下文设置。')); - const data = Object.fromEntries(new FormData(form)); - return { baseUrl: data.baseUrl, apiKey: data.apiKey, model: data.model, - contextWindowTokens: models.find(entry => entry.id === data.model)?.contextWindowTokens ?? 0, jevApiKey: data.jevApiKey, - policy: { mode: $('#adaptive-mode').checked ? 'adaptive' : 'manual', effort: data.effort, - classifierModel: data.classifierModel, models, routes: captureRoutes() } }; - } - function applyText(config) { - if (!config.configured) return t('保存后启动 Host'); - return t({ applied: '配置已应用', waiting: '任务结束后应用', pending: '任务结束后应用', error: '配置应用失败,请检查 Host 日志' }[config.reload.status] ?? '配置已保存'); - } - function status(state, isActive) { - active = isActive; - if (!loaded) { render(state.model); loaded = true; } - form.elements.apiKey.placeholder = state.model.hasApiKey ? t('已保存,留空保留') : t('输入模型服务的 API Key'); - $('#model-apply-title').textContent = applyText(state.model); - if (active && $('#adaptive-mode').checked) routingLog.load(); - } - const showError = error => { $('#model-error').textContent = error.message; $('#model-error').hidden = false; }; + function profileRouteReferences(profileId) { + const entries = []; + const uses = route => route?.profileId === profileId || route?.fallbacks?.some(item => item.profileId === profileId); + if (uses(config.defaultRoute)) entries.push(t('默认路由')); + for (const [agentId, route] of Object.entries(config.botRoutes)) if (uses(route)) + entries.push(agents.find(agent => agent.id === agentId)?.name ?? agentId); + return entries; + } + function renderProfiles() { + $('#add-model-profile').disabled = !config.providers.length; + profilesRoot.replaceChildren(); + if (!config.profiles.length) { + profilesRoot.append(empty(t('还没有模型档案'), t('每个档案绑定一个服务、模型和可用思考强度。'))); + return; + } + for (const profile of config.profiles) { + const provider = providerById(profile.providerId), references = profileRouteReferences(profile.id); + const test = iconButton('pulse', t('测试连接')); + test.onclick = () => busy(test, () => testProfile(profile)).catch(error => toast(error.message, true)); + const more = menu(t('{0} 的更多操作', profile.name), [ + { label: t('编辑'), run: () => showProfile(profile) }, + { label: t('删除'), danger: true, disabled: references.length > 0, run: trigger => busy(trigger, async () => { + if (!await confirmAction({ title: t('删除“{0}”?', profile.name), message: t('请先从 {0} 移除此档案。', references.join('、')), action: t('删除') })) return; + config.profiles = config.profiles.filter(item => item.id !== profile.id); markDirty(); render(); + }) }, + ]); + const effortText = profile.efforts.length ? profile.efforts.map(level => t(levelLabels[level])).join(' · ') : t('仅模型默认'); + profilesRoot.append(item({ icon: 'model', title: profile.name, badges: [badge(profile.model)], + meta: [`${provider?.name ?? profile.providerId} · ${effortText}`, t('上下文 {0} · 摘要 {1}', formatTokenCount(profile.contextWindowTokens), formatTokenCount(profile.summaryThresholdTokens))], + actions: [test, more] })); + } + } + function renderDefaultRoute() { + defaultRoot.replaceChildren(); + if (!config.profiles.length) { + defaultRoot.append(empty(t('还没有可路由的模型'), t('添加模型档案后,设置所有 Bot 的默认模型。'))); + return; + } + if (!config.defaultRoute) config.defaultRoute = { profileId: config.profiles[0].id, effort: 'default', fallbacks: [] }; + routeEditor(defaultRoot, config.defaultRoute, route => { config.defaultRoute = route; markDirty(); renderDefaultRoute(); }); + defaultRoot.append(node('p', 'hint', t('仅在主模型未输出任何内容时,才会按顺序尝试备用模型。'))); + } + function knownBots() { + const result = new Map(agents.map(agent => [agent.id, agent])); + for (const id of Object.keys(config.botRoutes)) if (!result.has(id)) result.set(id, { id, name: id, missing: true }); + return [...result.values()]; + } + function renderBots() { + botsRoot.replaceChildren(); + if (!config.profiles.length) { + botsRoot.append(empty(t('先设置默认路由'), t('模型档案准备好后,才可为单个 Bot 覆盖路由。'))); + return; + } + const bots = knownBots(); + if (!bots.length) { + botsRoot.append(empty(t('Host 未连接或尚无 Bot'), t('Host 连接后会在这里显示可覆盖的 Bot。'))); + return; + } + for (const bot of bots) { + const override = config.botRoutes[bot.id], route = override ?? config.defaultRoute; + const summarize = iconButton('archive', t('压缩上下文')); + summarize.disabled = Boolean(bot.missing || bot.isRunning || bot.isGroup); + summarize.onclick = () => busy(summarize, async () => { + if (!await confirmAction({ title: t('压缩“{0}”的上下文?', bot.name), + message: t('将使用此 Bot 当前路由的模型生成摘要。原始对话会保留,并会消耗模型 Token。'), + action: t('开始压缩'), danger: false })) return; + const result = await api(`/admin/api/agents/${encodeURIComponent(bot.id)}/summarize`, { method: 'POST' }); + toast(result.message ?? t('上下文已压缩')); + await refresh(); + }).catch(error => toast(error.message, true)); + const edit = iconButton('edit', t('编辑 Bot 路由')); + edit.onclick = () => showBotRoute(bot); + botsRoot.append(item({ icon: 'share', title: bot.name, + badges: [badge(override ? t('已覆盖') : t('使用默认'), override ? 'accent' : '')], + meta: [routeDescription(route), bot.missing ? t('当前 Host 未报告此 Bot;保存时会保留其路由。') : ''], actions: [summarize, edit] })); + } + } + function render() { renderProviders(); renderProfiles(); renderDefaultRoute(); renderBots(); } - form.elements.model.addEventListener('change', () => efforts(form.elements.effort, form.elements.model.value, 'default')); - $('#adaptive-mode').addEventListener('change', () => { mode(); if ($('#adaptive-mode').checked) routingLog.load(); }); - $('#refresh-models').addEventListener('click', () => busy($('#refresh-models'), async () => { - try { - const result = await api('/admin/api/model/catalog', { method: 'POST', body: input() }); - policy.routes = captureRoutes(); - models = result.models.map(item => models.find(old => old.id === item.id) ?? { id: item.id, efforts: item.efforts }); - const current = form.elements.model.value; - choices(form.elements.model, models.map(item => [item.id, item.id]), current); - efforts(form.elements.effort, form.elements.model.value, form.elements.effort.value); - renderRoutes(); renderCapabilities(); toast(t('模型列表已更新')); - } catch (error) { toast(error.message, true); } - })); - $('#add-model').addEventListener('click', () => { - if (!form.reportValidity()) return; - const field = $('#custom-model'), id = field.value.trim(); - if (!id || models.some(item => item.id === id)) return; - policy.routes = captureRoutes(); models.push({ id, efforts: [] }); field.value = ''; - choices(form.elements.model, models.map(item => [item.id, item.id]), form.elements.model.value); - renderRoutes(); renderCapabilities(); - }); - $('#test-routing').addEventListener('click', () => busy($('#test-routing'), async () => { - const task = $('#routing-task').value.trim(); if (!task) return; + function showProvider(entry) { + const current = entry ? clone(entry) : { id: uid('provider'), name: '', apiFormat: 'openai', baseUrl: '' }; + const { form: editForm, title, body, submit, dialog } = providerEditor; + body.replaceChildren(); editForm.reset(); title.textContent = t(entry ? '编辑模型服务' : '添加模型服务'); + const name = formField(body, 'name', '名称'), apiFormat = formSelect(body, 'apiFormat', '接口格式'); + choice(apiFormat, formats, current.apiFormat); + const baseUrl = formField(body, 'baseUrl', 'Base URL', 'url'), apiKey = formField(body, 'apiKey', 'API Key', 'password'); + name.required = true; baseUrl.required = true; name.value = current.name; baseUrl.value = current.baseUrl; + apiKey.placeholder = providerHasKey(current) ? t('已保存,留空保留') : t('输入 API Key'); + apiFormat.onchange = () => { if (!baseUrl.value) baseUrl.value = defaultUrls[apiFormat.value]; }; + editForm.onsubmit = event => { event.preventDefault(); if (!editForm.reportValidity()) return; busy(submit, async () => { + const next = { ...current, name: name.value.trim(), apiFormat: apiFormat.value, baseUrl: baseUrl.value.trim() }; + if (apiKey.value.trim()) pendingKeys.set(next.id, apiKey.value.trim()); + config.providers = [...config.providers.filter(provider => provider.id !== next.id), next]; markDirty(); dialog.close(); render(); + }).catch(error => toast(error.message, true)); }; + dialog.showModal(); name.focus(); + } + function addEffortControls(parent, selected) { + const group = node('fieldset', 'check-list'); group.append(node('legend', 'field', t('可用思考强度'))); + for (const level of levels) { + const label = node('label', 'check'), input = document.createElement('input'); + input.type = 'checkbox'; input.name = `effort-${level}`; input.value = level; input.checked = selected.includes(level); + label.append(input, node('span', '', t(levelLabels[level]))); group.append(label); + } + parent.append(group); + } + function showProfile(entry) { + if (!config.providers.length) return; + const current = entry ? clone(entry) : { id: uid('profile'), name: '', providerId: config.providers[0].id, model: '', efforts: [], + contextWindowTokens: defaultContextWindowTokens, summaryThresholdTokens: defaultSummaryThresholdTokens }; + const { form: editForm, title, body, submit, dialog } = profileEditor; + body.replaceChildren(); editForm.reset(); title.textContent = t(entry ? '编辑模型档案' : '添加模型档案'); + const name = formField(body, 'name', '名称'), providerId = formSelect(body, 'providerId', '模型服务'); + providerOptions(providerId, current.providerId); + const modelField = node('label', 'field', t('模型 ID')), modelRow = node('div', 'inline-field'), model = document.createElement('input'); + model.name = 'model'; model.required = true; model.value = current.model; model.spellcheck = false; + const list = document.createElement('datalist'); list.id = `model-catalog-${current.id}`; model.setAttribute('list', list.id); + const catalog = node('button', 'btn btn-sm', t('同步模型')); catalog.type = 'button'; + const catalogSelect = document.createElement('select'); catalogSelect.hidden = true; catalogSelect.setAttribute('aria-label', t('从同步列表选择模型')); + modelRow.append(model, catalog); modelField.append(modelRow, catalogSelect, list); body.append(modelField); + addEffortControls(body, current.efforts ?? []); + const contextFields = node('div', 'field-grid'); + const capacity = formField(contextFields, 'contextWindowTokens', '上下文容量'), threshold = formField(contextFields, 'summaryThresholdTokens', '摘要阈值'); + capacity.placeholder = t('未知'); threshold.placeholder = t('原策略'); capacity.value = formatTokenCount(current.contextWindowTokens); threshold.value = formatTokenCount(current.summaryThresholdTokens); + body.append(contextFields, node('p', 'hint', t('支持 1M、400K。同步后会自动填入上下文容量和摘要阈值。'))); + let catalogModels = new Map(); + const applyCatalogModel = (modelId, { onlyMissingContext = false } = {}) => { + const entry = catalogModels.get(modelId); + const values = entry?.efforts; + if (!values) return; + for (const level of levels) editForm.elements[`effort-${level}`].checked = values.includes(level); + const currentCapacity = parseTokenCount(capacity.value), currentThreshold = parseTokenCount(threshold.value); + if (Number.isSafeInteger(entry.contextWindowTokens) && entry.contextWindowTokens > 0 && + (!onlyMissingContext || !currentCapacity || !currentThreshold)) { + capacity.value = formatTokenCount(entry.contextWindowTokens); + threshold.value = formatTokenCount(entry.summaryThresholdTokens ?? 0); + } + }; + model.onchange = () => applyCatalogModel(model.value); + providerId.onchange = () => { catalogModels = new Map(); catalogSelect.hidden = true; catalogSelect.replaceChildren(); list.replaceChildren(); }; + catalogSelect.onchange = () => { + if (!catalogSelect.value) return; + model.value = catalogSelect.value; applyCatalogModel(model.value); + }; + catalog.onclick = () => busy(catalog, async () => { + const provider = providerById(providerId.value); + if (!provider) throw new Error(t('请先选择模型服务。')); + const result = await api('/admin/api/model/catalog', { method: 'POST', body: { provider: serializedProvider(provider) } }); + catalogModels = new Map(result.models.map(candidate => [candidate.id, candidate])); + list.replaceChildren(...result.models.map(candidate => new Option(candidate.id, candidate.id))); + catalogSelect.replaceChildren(new Option(t('从同步列表选择模型'), ''), ...result.models.map(candidate => new Option(candidate.id, candidate.id))); + catalogSelect.value = result.models.some(candidate => candidate.id === model.value) ? model.value : ''; + if (catalogSelect.value) applyCatalogModel(model.value, { onlyMissingContext: true }); + catalogSelect.hidden = false; toast(t('已同步 {0} 个模型', result.models.length)); + }).catch(error => toast(error.message, true)); + editForm.onsubmit = event => { event.preventDefault(); if (!editForm.reportValidity()) return; busy(submit, async () => { + const contextWindowTokens = parseTokenCount(capacity.value), summaryThresholdTokens = parseTokenCount(threshold.value); + if (!Number.isFinite(contextWindowTokens) || !Number.isFinite(summaryThresholdTokens)) throw new Error(t('请输入 0–100M 的整数 Token 数,如 1M、400K。')); + if (summaryThresholdTokens && (!contextWindowTokens || summaryThresholdTokens >= contextWindowTokens)) throw new Error(t('摘要阈值必须小于上下文容量。')); + const next = { ...current, name: name.value.trim(), providerId: providerId.value, model: model.value.trim(), + efforts: levels.filter(level => editForm.elements[`effort-${level}`].checked), contextWindowTokens, summaryThresholdTokens }; + config.profiles = [...config.profiles.filter(profile => profile.id !== next.id), next]; + if (!config.defaultRoute) config.defaultRoute = { profileId: next.id, effort: 'default', fallbacks: [] }; + markDirty(); dialog.close(); render(); + }).catch(error => toast(error.message, true)); }; + dialog.showModal(); name.focus(); + } + function showBotRoute(bot) { + const { form: editForm, title, body, submit, dialog } = botEditor; + let useDefault = !config.botRoutes[bot.id], route = routeCopy(config.botRoutes[bot.id] ?? config.defaultRoute); + body.replaceChildren(); editForm.reset(); title.textContent = bot.name; + const toggleLine = node('label', 'check'), toggle = document.createElement('input'); + toggle.type = 'checkbox'; toggle.checked = useDefault; toggleLine.append(toggle, node('span', '', t('使用默认路由'))); body.append(toggleLine); + const routeRoot = node('div', 'dialog-group'); body.append(routeRoot); + const draw = () => { + routeRoot.replaceChildren(); routeRoot.hidden = useDefault; + if (!useDefault) routeEditor(routeRoot, route, value => { route = value; draw(); }); + }; + toggle.onchange = () => { useDefault = toggle.checked; if (!useDefault && !route) route = routeCopy(config.defaultRoute); draw(); }; + draw(); + editForm.onsubmit = event => { event.preventDefault(); busy(submit, async () => { + if (useDefault) delete config.botRoutes[bot.id]; else config.botRoutes[bot.id] = routeCopy(route); + markDirty(); dialog.close(); renderBots(); + }).catch(error => toast(error.message, true)); }; + dialog.showModal(); + } + function updateAgents(next) { + const entries = (next ?? []).map(agent => ({ id: agent.id, name: agent.name, isGroup: Boolean(agent.isGroup), isRunning: Boolean(agent.isRunning) })) + .filter(agent => typeof agent.id === 'string' && typeof agent.name === 'string'); + const signature = JSON.stringify(entries); + if (signature === agentSignature) return; + agents = entries; agentSignature = signature; + if (loaded) renderBots(); + } + function showError(error) { $('#model-error').textContent = error.message; $('#model-error').hidden = false; } + function setIcon(target, name, label) { + const source = iconButton(name, t(label)); target.innerHTML = source.innerHTML; target.title = t(label); + } + + setIcon($('#add-model-provider'), 'plus', '添加模型服务'); + setIcon($('#add-model-profile'), 'plus', '添加模型档案'); + $('#add-model-provider').onclick = () => showProvider(); + $('#add-model-profile').onclick = () => showProfile(); + setIcon($('#refresh-model-bots'), 'refresh', '刷新 Bot'); + $('#refresh-model-bots').onclick = () => busy($('#refresh-model-bots'), refresh).catch(error => toast(error.message, true)); + setIcon($('#refresh-routing'), 'refresh', '刷新'); + $('#refresh-routing').onclick = () => routingLog.load(); + form.onsubmit = event => { event.preventDefault(); $('#model-error').hidden = true; busy(event.submitter, async () => { try { - const result = await api('/admin/api/model/classify', { method: 'POST', body: { ...input(), task } }); - $('#routing-result').textContent = `${result.model} · ${t(levelLabels[result.effort] ?? result.effort)}${result.fallback ? ` · ${t('分类器暂不可用,使用中等任务规则')}` : ''}`; - routingLog.load(); - } catch (error) { toast(error.message, true); } - })); - $('#refresh-routing').addEventListener('click', () => routingLog.load()); - form.addEventListener('submit', event => { - event.preventDefault(); - $('#model-error').hidden = true; - busy(form.querySelector('[type=submit]'), async () => { - try { - await api('/admin/api/model', { method: 'PUT', body: input() }); - form.elements.apiKey.value = ''; form.elements.jevApiKey.value = ''; - toast(t('配置已保存')); - await refresh(); - } catch (error) { showError(error); } - }); - }); - $('#test-model').addEventListener('click', () => { - if (!form.reportValidity()) return; - busy($('#test-model'), async () => { - $('#model-error').hidden = true; - try { toast((await api('/admin/api/model/test', { method: 'POST', body: input() })).message); } - catch (error) { showError(error); } - }); - }); + if (legacyAdaptive && !await confirmAction({ + title: t('迁移旧版模型路由?'), + message: t('保存后会改为按 Bot 选择模型,旧版按任务难度路由和 Jev 选择将不再生效。'), + action: t('迁移并保存'), + })) return; + const result = await api('/admin/api/model', { method: 'PUT', body: input() }); + legacyRouting = false; legacyAdaptive = false; + $('#legacy-routing-notice').hidden = true; + setConfig(result); toast(t('配置已保存')); await refresh(); + } catch (error) { showError(error); } + }); }; + return { - status, - async load() { if ($('#adaptive-mode').checked) await routingLog.load(); }, - reset() { loaded = false; form.reset(); }, + status(next, isActive) { + active = isActive; updateAgents(next.host?.agents); + if (!loaded) setConfig(next.model); + else if (!dirty) $('#model-apply-title').textContent = applyText(next.model); + if (active) routingLog.load(); + }, + async load() { + if (!dirty) setConfig(await api('/admin/api/model')); + if (active) await routingLog.load(); + }, + reset() { config = emptyRouting(); pendingKeys = new Map(); loaded = false; dirty = false; active = false; agents = []; + agentSignature = ''; legacyRouting = false; legacyAdaptive = false; $('#legacy-routing-notice').hidden = true; form.reset(); }, }; } diff --git a/host/server/public/navigation.js b/host/server/public/navigation.js index 19b444e54997cf6cba71f8d491fe503d1743a5b7..43b144dae0c77ded893521ad74e551a6bfc1103b 100644 --- a/host/server/public/navigation.js +++ b/host/server/public/navigation.js @@ -7,7 +7,7 @@ export const groups = [ { items: [['overview', '概览', 'overview']] }, { title: '模型服务', items: [['model', '对话模型', 'model'], ['speech', '语音', 'voice'], ['media', '图片与视频', 'image'], ['web-services', '联网工具', 'globe']] }, { title: 'Agent', items: [['harness', '内置能力', 'toggles'], ['skills', '技能', 'book'], ['apps', '应用', 'plug'], ['prompts', '提示词', 'text']] }, - { title: '设备与网络', items: [['devices', '设备与通知', 'devices'], ['network', '远程访问', 'link'], ['execution', '执行环境', 'monitor']] }, + { title: '设备与网络', items: [['devices', '设备与通知', 'devices'], ['web-client', '网页版', 'external'], ['network', '远程访问', 'link'], ['execution', '执行环境', 'monitor']] }, { title: '协作与集成', items: [['federation', 'Host 协作', 'swap'], ['webhooks', 'Webhook', 'bolt'], ['sharing', '分享', 'share']] }, ]; diff --git a/host/server/public/overview.js b/host/server/public/overview.js index 7941863b8a23789e8af65f19cedf82340c9f5175..286507f6f66fd786766c9fc954737f78d52b7613 100644 --- a/host/server/public/overview.js +++ b/host/server/public/overview.js @@ -33,6 +33,7 @@ const summaries = { function headline(state, bots) { const running = bots.filter(bot => bot.isRunning).length; if (!state.model.configured) return [t('配置对话模型'), t('后启动 Host')]; + if (state.host.waitingForExecutionNode) return [t('配置执行节点'), t('后启动 Host')]; if (!state.host.connected) return [t('等待 Host'), t('启动')]; if (running) return [t('{0} 个 Bot', running), t('正在工作')]; return bots.length ? [t('Host 就绪'), t('{0} 个 Bot 待命', bots.length)] : [t('Host 就绪'), '']; @@ -43,6 +44,7 @@ export function createOverview({ api, status: current }) { panel.innerHTML = html(`

+

@@ -73,7 +75,8 @@ export function createOverview({ api, status: current }) { } function renderAttention(state) { const items = []; - if (!state.model.configured) items.push(['还没有对话模型', '填写兼容 OpenAI 的接口后,Host 才会启动。', '配置模型', 'model']); + if (!state.model.configured) items.push(['还没有对话模型', '配置 OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages 接口后,Host 才会启动。', '配置模型', 'model']); + if (state.host.waitingForExecutionNode) items.push(['需要执行节点', '分机部署需要连接独立的执行电脑,Bot 才能开始聊天。', '配置节点', 'execution']); if (!state.devices.some(device => !device.revokedAt)) items.push(['还没有配对设备', '用配对码连接电脑或手机客户端。', '配对设备', 'devices']); $('#attention').hidden = !items.length; $('#attention-list').replaceChildren(...items.map(([title, hint, action, view]) => { @@ -86,11 +89,20 @@ export function createOverview({ api, status: current }) { } function render(state) { const bots = state.host.agents.filter(agent => !agent.isGroup); + $('#hero-status-error').hidden = true; + $('#hero-host').hidden = $('#bot-crew').hidden = $('#hero-usage').hidden = false; $('#hero-title').replaceChildren(...headline(state, bots).filter(Boolean).map(line => node('span', '', line))); crew.render(state, bots); renderAttention(state); for (const [view, [paths, summarize]] of Object.entries(summaries)) if (!paths) show(view, summarize(null, state)); } + function statusUnavailable(title, detail = '') { + $('#hero-title').textContent = title; + $('#hero-status-error').textContent = detail; + $('#hero-status-error').hidden = !detail; + $('#hero-host').hidden = $('#bot-crew').hidden = $('#hero-usage').hidden = $('#attention').hidden = true; + for (const [view, [paths]] of Object.entries(summaries)) if (!paths) show(view, ['—', false]); + } async function loadUsage() { const usage = await api(`/admin/api/usage?timeZone=${encodeURIComponent(Intl.DateTimeFormat().resolvedOptions().timeZone)}`); const compact = new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: 1 }); @@ -106,5 +118,5 @@ export function createOverview({ api, status: current }) { catch { show(view, ['—', false]); } })]); } - return { load, status: render }; + return { load, status: render, statusUnavailable }; } diff --git a/host/server/public/routing-log.js b/host/server/public/routing-log.js index 9aff7c28b45283071a12710d087a2d09cf0b3a9e..38bae0d1ecd59bf15a383e799e81c2c32e9c7e1a 100644 --- a/host/server/public/routing-log.js +++ b/host/server/public/routing-log.js @@ -5,6 +5,26 @@ const tiers = { routine: '一般任务', reasoning: '中等任务', expert: '困 const efforts = { none: '无', low: '轻度', medium: '中度', high: '高度', xhigh: '超高', max: '最高', default: '模型默认' }; const sources = { jev: '思考强度由 Jev 选择', rule: '使用规则指定的思考强度', model: '使用模型可用强度' }; +function fallbackEntry(item) { + const entry = node('details', 'disclosure routing-entry'), summary = node('summary'), copy = node('span', 'routing-copy'); + const from = item.from ?? {}, to = item.to ?? {}; + entry.dataset.id = item.id; + const headline = node('span', 'routing-headline'); + headline.append(node('strong', '', item.agentId || t('默认路由')), badge(t('模型回退'), 'warn'), node('time', 'hint', date(item.at))); + const target = to?.profileName ?? to?.profileId ?? t('没有可用备用模型'); + copy.append(headline, node('span', 'hint', `${from.profileName ?? from.profileId ?? t('主模型')} → ${target}`)); + summary.append(copy); entry.append(summary); + const details = [ + `${t('服务')}:${from.providerName ?? from.providerId ?? t('未知')} → ${to?.providerName ?? to?.providerId ?? t('未选择')}`, + `${t('失败类别')}:${item.reason ?? t('未知')}${item.session ? ` · ${t('会话')}:${item.session}` : ''}`, + ]; + if (item.skipped?.length) details.push(`${t('跳过同 API Key 的模型')}:${item.skipped.map(value => + value.profileName ?? value.profileId ?? value.model).join('、')}`); + const body = node('div', 'routing-body'); + details.forEach(value => body.append(node('p', 'hint', value))); entry.append(body); + return entry; +} + export function createRoutingLog({ api }) { let pending = false, signature; async function load() { @@ -17,8 +37,11 @@ export function createRoutingLog({ api }) { if (signature === next) return; signature = next; const open = new Set([...root.querySelectorAll('details[open]')].map(row => row.dataset.id)); - if (!items.length) { root.replaceChildren(empty(t('暂无分类记录'))); return; } + if (!items.length) { root.replaceChildren(empty(t('暂无路由记录'))); return; } root.replaceChildren(...items.map(item => { + if (item.kind === 'model-fallback') { + const entry = fallbackEntry(item); entry.open = open.has(item.id); return entry; + } const entry = node('details', 'disclosure routing-entry'), summary = node('summary'), copy = node('span', 'routing-copy'); entry.dataset.id = item.id; entry.open = open.has(item.id); const headline = node('span', 'routing-headline'); diff --git a/host/server/public/sharing.js b/host/server/public/sharing.js index 23e72808158488dfde826f30e42ece860579a9be..079efb4a390f922d5de07fe78644b07bb02e555b 100644 --- a/host/server/public/sharing.js +++ b/host/server/public/sharing.js @@ -75,7 +75,7 @@ export function createSharingEditor({ api, toast, act }) { await api(`/admin/api/sharing/${entry.id}`, { method: 'DELETE' }); await load(); }) }, ]); - return item({ tile: icon(entry.kind === 'bot' ? 'share' : 'book'), title: entry.name, description: entry.description, + return item({ icon: entry.kind === 'bot' ? 'share' : 'book', title: entry.name, description: entry.description, badges: [badge(entry.active ? t('已发布') : t('草稿'), entry.active ? 'success' : '')], meta: [`${entry.kind === 'bot' ? 'Bot' : t('技能')} · v${entry.version}`], actions: [open, more] }); }) : [empty(t('暂无分享'), t('发布技能,或导入别人分享的 Bot 与技能 ZIP。'))])); diff --git a/host/server/public/skills.js b/host/server/public/skills.js index a597a2b7927008cea41adaa8172739e60e636518..dd65344089bc9ea2ecaf831911303582f787d6fc 100644 --- a/host/server/public/skills.js +++ b/host/server/public/skills.js @@ -58,7 +58,7 @@ export function createSkillsEditor({ api, toast, act }) { if (!await confirmAction({ title: t('删除“{0}”?', entry.name), message: t('Bot 将无法再使用此技能。'), action: t('删除') })) return; await api(`/admin/api/skills/${entry.id}`, { method: 'DELETE' }); await load(); }) }]); - list.append(item({ tile: icon('book'), title: entry.name, description: entry.description, + list.append(item({ icon: 'book', title: entry.name, description: entry.description, meta: [`${entry.source.startsWith('plugin:') ? t('应用附带') : entry.source === 'host' ? 'Host' : entry.source} · ${entry.current.slice(0, 8)}`], actions: [enabled, edit, more] })); } } diff --git a/host/server/public/stage.css b/host/server/public/stage.css index abe0ba65c74d3055cb44c8620322c3b6e1bb22fd..fcf9cbfd7b2e002ef89b7088567d6e85bf2c4821 100644 --- a/host/server/public/stage.css +++ b/host/server/public/stage.css @@ -151,8 +151,7 @@ label.composer { padding-right: 22px; } align-items: end; } .hero-copy { display: flex; flex-direction: column; gap: 16px; grid-area: copy; align-self: start; } -.hero-title { display: flex; flex-direction: column; font: 600 68px/1.02 var(--font-sans); letter-spacing: -0.04em; } -.hero-title span { white-space: nowrap; } +.hero-title { display: flex; flex-direction: column; font: 600 68px/1.02 var(--font-sans); letter-spacing: -0.04em; overflow-wrap: anywhere; } .hero-usage { color: var(--sand-text-secondary); font: 17px/24px var(--font-sans); font-variant-numeric: tabular-nums; } .hero-host { grid-area: host; align-self: center; } .hero-host .face { --size: 196px; box-shadow: inset calc(var(--size) * -.05) calc(var(--size) * -.07) calc(var(--size) * .14) #0000002e, 0 calc(var(--size) * .14) calc(var(--size) * .22) calc(var(--size) * -.1) #00000059; } @@ -172,7 +171,7 @@ label.composer { padding-right: 22px; } @media (max-width: 640px) { .page.overview { gap: 36px; padding-top: 28px; } .hero { grid-template-areas: "copy host" "crew crew"; gap: 28px 12px; align-items: start; } - .hero-title { font-size: 40px; } + .hero-title { font-size: 32px; letter-spacing: 0; text-wrap: balance; } .hero-usage { font-size: 15px; line-height: 22px; } .hero-host { align-self: start; } .hero-host .face { --size: 84px; } diff --git a/host/server/public/ui.js b/host/server/public/ui.js index 18d6f3c7ded5987c987536931464f30c7247fdc0..622fb50a1329513a83c46606713788b53a87014b 100644 --- a/host/server/public/ui.js +++ b/host/server/public/ui.js @@ -1,5 +1,5 @@ import { t, locale } from './i18n.js'; -import { icon } from './icons.js'; +import { icon, isBuiltinIcon } from './icons.js'; export const $ = (selector, root = document) => root.querySelector(selector); export const all = (selector, root = document) => [...root.querySelectorAll(selector)]; @@ -94,11 +94,11 @@ export function toggle(checked, label) { return input; } -/** A list row: leading tile, title with badges, meta lines and trailing actions. */ -export function item({ tile, image, title, badges = [], meta = [], description, actions = [] }) { +/** A list row: built-in icon name, image, title with badges, meta lines and trailing actions. */ +export function item({ icon: iconName, tile, image, title, badges = [], meta = [], description, actions = [] }) { const row = node('div', 'item'), lead = node('span', 'item-icon'), copy = node('div', 'item-copy'); if (image) { const img = document.createElement('img'); img.src = image; img.alt = ''; lead.append(img); } - else if (tile?.startsWith?.(' void busy(preview, async () => { - clearAudio(); error.hidden = true; controller?.abort(); controller = new AbortController(); + clearAudio(); error.hidden = true; try { - const response = await fetch('/admin/api/voice/test', { method: 'POST', credentials: 'same-origin', - headers: { 'content-type': 'application/json', 'x-grokbot-csrf': '1' }, signal: controller.signal, - body: JSON.stringify({ text: $('#voice-preview-text').value.trim() }) }); - if (!response.ok) throw new Error((await response.json()).error); - audioUrl = URL.createObjectURL(await response.blob()); player.src = audioUrl; player.hidden = false; + const audio = await api('/admin/api/voice/test', { method: 'POST', + binary: true, body: { text: $('#voice-preview-text').value.trim() } }); + audioUrl = URL.createObjectURL(audio); player.src = audioUrl; player.hidden = false; await player.play().catch(() => {}); } catch (e) { if (e.name !== 'AbortError') { error.textContent = errorText(e.message); error.hidden = false; } } })); - return { load, reset() { controller?.abort(); loaded = false; saved = undefined; clearAudio(); form.reset(); controls(); } }; + return { load, reset() { loaded = false; saved = undefined; clearAudio(); form.reset(); controls(); } }; } diff --git a/host/server/public/web-client.js b/host/server/public/web-client.js new file mode 100644 index 0000000000000000000000000000000000000000..9ba3d17399763c643b8546ce0d11264a42be8eef --- /dev/null +++ b/host/server/public/web-client.js @@ -0,0 +1,108 @@ +import { t, html } from './i18n.js'; +import { $, confirmAction, date } from './ui.js'; +import { icon } from './icons.js'; + +const MiB = 1024 * 1024; + +/** Uploads with progress; fetch cannot report how much of a request body has been sent. */ +function upload(file, onProgress) { + return new Promise((resolve, reject) => { + const request = new XMLHttpRequest(); + request.open('PUT', '/admin/api/web-client'); + request.setRequestHeader('content-type', 'application/zip'); + request.setRequestHeader('x-grokbot-csrf', '1'); + request.upload.onprogress = event => { if (event.lengthComputable) onProgress(event.loaded / event.total); }; + request.onload = () => { + let value = null; + try { value = JSON.parse(request.responseText); } catch {} + if (request.status >= 200 && request.status < 300 && value) resolve(value); + else reject(new Error(typeof value?.error === 'string' ? t(value.error) : t('请求失败 ({0})', request.status))); + }; + request.onerror = () => reject(new Error(t('无法连接管理服务。'))); + request.send(file); + }); +} + +function deviceName() { + const agent = navigator.userAgent; + const system = /iPhone/.test(agent) ? 'iPhone' : /iPad/.test(agent) ? 'iPad' : /Android/.test(agent) ? 'Android' + : /Mac OS X/.test(agent) ? 'Mac' : /Windows/.test(agent) ? 'Windows' : /Linux/.test(agent) ? 'Linux' : ''; + const browser = /Edg\//.test(agent) ? 'Edge' : /Firefox\//.test(agent) ? 'Firefox' : /Chrome\//.test(agent) ? 'Chrome' : /Safari\//.test(agent) ? 'Safari' : ''; + return `${t('网页版')} · ${[system, browser].filter(Boolean).join(' ') || t('浏览器')}`.slice(0, 80); +} + +export function createWebClientPage({ api, toast, busy, refresh, copy }) { + $('[data-panel=web-client]').innerHTML = html(` +

访问

+ +
界面包未上传
+
网页地址在其他设备打开,输入「设备与通知」里创建的配对码登录 +
+
+

界面包

+
上传界面包在电脑上运行 node web/patchers/patch.mjs,生成 web/output/GrokBotLocal-web-1.1.0.zip 后上传。界面取自你自己下载的官方 Windows 安装包,只保存在这台 Host 上,未登录的访问者拿不到。 +
+
删除界面包网页版随之停用;已登录的浏览器仍列在「设备与通知」里,可在那里撤销
+
`); + let origin = location.origin; + + function render(value) { + const toggle = $('#web-client-enabled'); + toggle.checked = value.enabled; toggle.disabled = !value.installed; + $('#web-client-bundle').textContent = value.installed + ? t('界面 {0} · {1} 个文件 · {2} MB · 上传于 {3}', value.rendererVersion, value.files, (value.bytes / MiB).toFixed(1), date(value.installedAt)) + : t('未上传'); + $('#web-client-open').disabled = !value.available; + $('#web-client-remove').disabled = !value.installed; + $('#web-client-url').textContent = `${origin}/web/`; + const host = new URL(origin); + $('#web-client-insecure').hidden = host.protocol !== 'http:' || ['localhost', '127.0.0.1', '[::1]'].includes(host.hostname); + } + + $('#web-client-copy').onclick = () => copy(`${origin}/web/`); + $('#web-client-upload').onclick = () => $('#web-client-file').click(); + $('#web-client-file').onchange = () => { + const file = $('#web-client-file').files[0]; + $('#web-client-file').value = ''; + if (!file) return; + const control = $('#web-client-upload'); + busy(control, async () => { + try { + render(await upload(file, fraction => { control.textContent = t('正在上传 {0}%', Math.round(fraction * 100)); })); + toast(t('网页版界面包已安装')); + await refresh(); + } catch (error) { toast(error.message, true); } + }); + }; + $('#web-client-enabled').onchange = event => { + const enabled = event.target.checked; + busy(event.target, async () => { + try { render(await api('/admin/api/web-client', { method: 'PATCH', body: { enabled } })); toast(enabled ? t('网页版已启用') : t('网页版已停用')); } + catch (error) { event.target.checked = !enabled; toast(error.message, true); } + }); + }; + $('#web-client-remove').onclick = () => busy($('#web-client-remove'), async () => { + if (!await confirmAction({ title: t('删除网页版界面包?'), message: t('网页版会停用。之后要使用,需要重新上传界面包。'), action: t('删除') })) return; + try { render(await api('/admin/api/web-client', { method: 'DELETE' })); toast(t('网页版界面包已删除')); } + catch (error) { toast(error.message, true); } + }); + $('#web-client-open').onclick = () => { + // Opened before the request finishes, or the browser treats the new tab as an unrequested popup. + const opened = window.open('', '_blank'); + busy($('#web-client-open'), async () => { + try { + const { url } = await api('/admin/api/web-client/open', { method: 'POST', body: { deviceName: deviceName() } }); + if (opened) opened.location.href = url; else location.assign(url); + await refresh(); + } catch (error) { opened?.close(); toast(error.message, true); } + }); + }; + + return { + async load() { render(await api('/admin/api/web-client')); }, + status(state) { + if (state.publicUrl) origin = state.publicUrl; + if (state.webClient) render(state.webClient); + }, + }; +} diff --git a/host/server/public/web-login.css b/host/server/public/web-login.css new file mode 100644 index 0000000000000000000000000000000000000000..9ad625b06a6fa471696eead30559cd1e635d9f6d --- /dev/null +++ b/host/server/public/web-login.css @@ -0,0 +1,11 @@ +/* Sign-in page of the web client; the stage and composer come from stage.css. */ +html:has(#web-login) { background: #0e0e0e; } +.web-talk { gap: 16px; text-align: center; } +.web-talk h1 { margin: 0; font: 600 24px/32px var(--font-sans); } +.web-lead, .web-note, .web-device { margin: 0; color: var(--sand-text-secondary); font: 15px/22px var(--font-sans); } +.web-note { font-size: 13px; line-height: 20px; } +.web-form { position: relative; width: 100%; margin-top: 44px; } +.web-paired { display: grid; gap: 16px; width: 100%; } +.web-device { color: var(--sand-text-primary); } +.web-actions { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; } +.web-actions .btn { min-width: 140px; justify-content: center; } diff --git a/host/server/public/web-login.html b/host/server/public/web-login.html new file mode 100644 index 0000000000000000000000000000000000000000..a585af014626c98dad4d5ecc41562a08b2b51387 --- /dev/null +++ b/host/server/public/web-login.html @@ -0,0 +1,45 @@ + + + + + + + + Grok Bot + + + + + + + + + + + +
+
+ Grok Bot 网页版 +
+
+

登录网页版

+

在 Host 管理页「设备与通知」创建 6 位配对码,输入后即可在这个浏览器里使用你的 Bot。

+ + + + +
+
+
+ + diff --git a/host/server/public/web-login.js b/host/server/public/web-login.js new file mode 100644 index 0000000000000000000000000000000000000000..f31656dc2151cce88bcb36cab0e3a7882d434546 --- /dev/null +++ b/host/server/public/web-login.js @@ -0,0 +1,98 @@ +// Sign-in page of the web client (/web/login). A browser signs in with a pairing code from the +// admin page and receives an HttpOnly cookie; the interface itself is served only after that. +import { t, localize } from './i18n.js'; +import { $ } from './ui.js'; +import { createFace, lookAt, resetLook, blink } from './face.js'; + +localize(document.body); +const form = $('#web-form'), code = $('#web-code'), message = $('#web-message'), status = $('#web-status'); +const face = createFace(); +face.classList.add('login-face'); +$('#web-face').append(face); +blink(() => [face]); +addEventListener('pointermove', event => lookAt(face, event.clientX, event.clientY, 0.075)); +addEventListener('pointerleave', () => resetLook(face)); + +const say = text => { message.textContent = text; message.hidden = !text; }; +const note = text => { status.textContent = text; status.hidden = !text; }; +const next = () => { + const params = new URLSearchParams(location.search); + params.delete('expired'); + const query = params.toString(); + return `/web/${query ? `?${query}` : ''}`; +}; + +async function call(path, body) { + const response = await fetch(path, { + method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', cache: 'no-store', redirect: 'error', + headers: { 'content-type': 'application/json', 'x-grokbot-web': '1' }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + const value = await response.json().catch(() => null); + if (!response.ok) throw new Error(typeof value?.error === 'string' ? t(value.error) : t('请求失败 ({0})', response.status)); + return value; +} + +function deviceName() { + const agent = navigator.userAgent; + const system = /iPhone/.test(agent) ? 'iPhone' : /iPad/.test(agent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) ? 'iPad' + : /Android/.test(agent) ? 'Android' : /Mac OS X/.test(agent) ? 'Mac' : /Windows/.test(agent) ? 'Windows' : /Linux/.test(agent) ? 'Linux' : ''; + const browser = /Edg\//.test(agent) ? 'Edge' : /Firefox\//.test(agent) ? 'Firefox' : /Chrome\//.test(agent) ? 'Chrome' + : /Safari\//.test(agent) ? 'Safari' : ''; + return `${t('网页版')} · ${[system, browser].filter(Boolean).join(' ') || t('浏览器')}`.slice(0, 80); +} + +// Chinese input methods often type full-width characters; codes use letters and digits only. +let composing = false; +const tidy = () => { code.value = code.value.normalize('NFKC').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 6); }; +code.addEventListener('compositionstart', () => { composing = true; }); +code.addEventListener('compositionend', () => { composing = false; tidy(); }); +code.addEventListener('input', event => { if (!composing && !event.isComposing) tidy(); if (!message.hidden) say(''); }); + +form.addEventListener('submit', async event => { + event.preventDefault(); + if (composing) return; + tidy(); + if (code.value.length !== 6) { say(t('请输入 6 位配对码。')); code.focus(); return; } + $('.auth-talk').classList.add('pending'); + $('#web-submit').disabled = true; + try { + await call('/web/api/pair', { pairingKey: code.value, deviceName: deviceName() }); + // The click is the user gesture browsers require before asking about notifications. + if (typeof Notification === 'function' && Notification.permission === 'default') + await Promise.race([Notification.requestPermission().catch(() => {}), new Promise(resolve => setTimeout(resolve, 15000))]); + location.assign(next()); + } catch (error) { + say(error.message); + $('.auth-talk').classList.remove('pending'); + $('#web-submit').disabled = false; + } +}); + +$('#web-logout').addEventListener('click', async () => { + $('#web-logout').disabled = true; + try { await call('/web/api/logout', {}); location.reload(); } + catch (error) { note(error.message); $('#web-logout').disabled = false; } +}); +$('#web-open').href = next(); + +const insecure = location.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname); +$('#web-insecure').hidden = !insecure; +try { + const session = await call('/web/api/session'); + if (!session.available) { + $('#web-lead').hidden = true; + note(t('网页版还没有启用。请管理员在 Host 管理页「网页版」上传界面包并启用。')); + } else if (session.paired) { + $('#web-title').textContent = t('已登录'); + $('#web-lead').hidden = true; + $('#web-device').textContent = t('这个浏览器已登录为“{0}”。', session.deviceName ?? ''); + $('#web-paired').hidden = false; + } else { + form.hidden = false; + if (new URLSearchParams(location.search).has('expired')) say(t('登录已失效,请输入新的配对码。')); + code.focus(); + } +} catch (error) { + note(t('无法连接 Host:{0}', error.message)); +} diff --git a/host/server/public/webhooks.js b/host/server/public/webhooks.js index 0d3f64ec971ad5445d8f15c86d9d3b601529dbd9..5453298d0410a6ddb2173388c15d51d9aa230d77 100644 --- a/host/server/public/webhooks.js +++ b/host/server/public/webhooks.js @@ -44,7 +44,7 @@ export function createWebhookEditor({ api, toast, act }) { } async function loadEvents() { const events = await api('/admin/api/webhooks/events'), list = $('#hook-events'); - list.replaceChildren(...(events.length ? events.slice(0, 50).map(event => item({ tile: icon('bolt'), + list.replaceChildren(...(events.length ? events.slice(0, 50).map(event => item({ icon: 'bolt', title: hooks.find(hook => hook.id === event.hookId)?.name ?? event.hookId, description: event.detail, meta: [`${event.eventId} · ${new Date(event.receivedAt).toLocaleString(locale)}`], actions: [badge(t(states[event.state] ?? event.state), tones[event.state])] })) : [empty(t('暂无运行记录'))])); @@ -69,7 +69,7 @@ export function createWebhookEditor({ api, toast, act }) { await api(`/admin/api/webhooks/${hook.id}`, { method: 'DELETE' }); await load(); }) }, ]); - const row = item({ tile: icon('bolt'), title: hook.name, meta: [hook.path], actions: [enabled, editButton, more] }); + const row = item({ icon: 'bolt', title: hook.name, meta: [hook.path], actions: [enabled, editButton, more] }); row.querySelector('.item-meta').dataset.private = ''; return row; }) : [empty(t('还没有 Webhook'), t('外部系统发送签名事件后,由指定 Bot 执行任务。'))])); diff --git a/host/server/push-service.mjs b/host/server/push-service.mjs index d843aef97513b655ce5f11b0dcdb8ec49fbb1c26..a353d08e653b99a2315e640e36f60d074dc04754 100644 --- a/host/server/push-service.mjs +++ b/host/server/push-service.mjs @@ -24,7 +24,7 @@ export class PushService { const { provider = 'none', capable = false, authorization = 'notDetermined', environment = null, enabled = true, lastAttemptAt = null, lastDeliveredAt = null, lastError = null, registrationError = null } = value; return { ...device, deviceId: device.id, name: value.displayName || value.name || device.name, - kind: value.kind ?? (device.platform === 'ios' ? 'iphone' : 'mac'), + kind: ['android', 'web'].includes(device.platform) ? device.platform : value.kind ?? (device.platform === 'ios' ? 'iphone' : 'mac'), bundleId: value.bundleId ?? null, appVersion: value.appVersion ?? null, push: { provider, capable, authorization, environment, foreground: this.isForeground(device.id), enabled: enabled && !device.revokedAt, barkHost: value.bark?.host ?? null, @@ -71,7 +71,8 @@ export class PushService { next.name = input.name.trim(); } if (input.kind !== undefined) { - check(['iphone', 'ipad', 'mac', 'desktop'].includes(input.kind), 400, '设备类型无效'); next.kind = input.kind; + check(['iphone', 'ipad', 'mac', 'desktop'].includes(input.kind), 400, '设备类型无效'); + next.kind = input.kind === 'desktop' && ['windows', 'android', 'web'].includes(input.clientKind) ? input.clientKind : input.kind; } if (input.bundleId !== undefined) { check(validTopic(input.bundleId), 400, '设备 Bundle ID 无效'); next.bundleId = input.bundleId; diff --git a/host/server/storage.mjs b/host/server/storage.mjs index 9c977ef04265070f52e1a771b38e6c53e4bfc90b..7557005b798b13a8b8c06c51b2fdce0e21924331 100644 --- a/host/server/storage.mjs +++ b/host/server/storage.mjs @@ -2,6 +2,19 @@ import { randomBytes } from "node:crypto"; import { chmod, mkdir, open, readFile, rename, rm } from "node:fs/promises"; import { dirname } from "node:path"; +export async function syncRenamedDirectory(directory, { openFile = open, platform = process.platform } = {}) { + const handle = await openFile(directory, "r"); + try { + await handle.sync(); + } catch (error) { + // Windows does not support fsync on directory handles. The file itself was + // already synced before the rename, so retain the atomic replacement there. + if (!(platform === "win32" && error?.code === "EPERM")) throw error; + } finally { + await handle.close(); + } +} + export async function writePrivate(filename, text) { await mkdir(dirname(filename), { recursive: true, mode: 0o700 }); const temporary = `${filename}.${randomBytes(8).toString("hex")}.tmp`; @@ -13,12 +26,7 @@ export async function writePrivate(filename, text) { await file.close(); file = null; await rename(temporary, filename); - const directory = await open(dirname(filename), "r"); - try { - await directory.sync(); - } finally { - await directory.close(); - } + await syncRenamedDirectory(dirname(filename)); } finally { await file?.close(); await rm(temporary, { force: true }); diff --git a/host/server/web-client.mjs b/host/server/web-client.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8661bc79fb339749d0e5f66377e8ccb0cfd197fd --- /dev/null +++ b/host/server/web-client.mjs @@ -0,0 +1,300 @@ +// The web client: a bundle built by web/patchers/patch.mjs from the administrator's own copy of +// the official Grok Bot Windows installer, uploaded from the admin page and served at /web/. +// +// - The bundle contains the official interface, so every one of its files goes only to a browser +// that signed in with a pairing code. Nothing of it is public; the sign-in page is Host code. +// - A signed-in browser holds an HttpOnly, SameSite=Strict cookie with its device token. The +// device API accepts that cookie only together with the `x-grokbot-web: 1` header, which +// another site cannot send without a CORS preflight the Host never grants, and only from the +// Host's own origin. Bundle files are plain GETs and carry Cross-Origin-Resource-Policy. +// - Upload replaces the whole bundle at once: it is checked against its own manifest, unpacked +// beside the current one and swapped in by renaming. +import { createHash, randomBytes } from 'node:crypto'; +import { createReadStream } from 'node:fs'; +import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { promisify } from 'node:util'; +import { gzip as gzipCallback, inflateRawSync } from 'node:zlib'; +import { JsonStore } from './storage.mjs'; +import { check, cookie } from './security.mjs'; + +const gzip = promisify(gzipCallback); +export const WEB_COOKIE = 'grokbot_web'; +export const BUNDLE_SCHEMA = 'grokbot-web-bundle/v1'; +export const MAX_BUNDLE_BYTES = 256 * 1024 * 1024; +const MAX_FILES = 5000, MAX_FILE_BYTES = 64 * 1024 * 1024, MAX_TOTAL_BYTES = 512 * 1024 * 1024; +const COOKIE_SECONDS = 400 * 24 * 60 * 60; +// The files the web client cannot start without; the rest is whatever the interface contains. +const REQUIRED = ['renderer/index.html', 'client/boot-data.js', 'client/compat.js', 'client/bridge.js', 'client/native.js', + 'client/web-shell.js', 'client/official-preload.js', 'client/vnc-bridge.js', 'client/vnc-preload.js', 'client/icon.png']; +const TYPES = { + html: 'text/html; charset=utf-8', js: 'text/javascript; charset=utf-8', mjs: 'text/javascript; charset=utf-8', + css: 'text/css; charset=utf-8', json: 'application/json; charset=utf-8', map: 'application/json; charset=utf-8', + svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', + ico: 'image/x-icon', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', wav: 'audio/wav', + mp3: 'audio/mpeg', ogg: 'audio/ogg', mp4: 'video/mp4', webm: 'video/webm', wasm: 'application/wasm', txt: 'text/plain; charset=utf-8', +}; +const COMPRESSIBLE = new Set(['html', 'js', 'mjs', 'css', 'json', 'map', 'svg', 'txt', 'wasm']); +const extension = name => /\.([a-z0-9]+)$/i.exec(name)?.[1].toLowerCase() ?? ''; +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); + +const CRC_TABLE = Array.from({ length: 256 }, (_, n) => { + for (let i = 0; i < 8; i++) n = n & 1 ? 0xedb88320 ^ n >>> 1 : n >>> 1; + return n >>> 0; +}); +function crc32(bytes) { + let n = 0xffffffff; + for (let i = 0; i < bytes.length; i++) n = CRC_TABLE[(n ^ bytes[i]) & 255] ^ n >>> 8; + return (n ^ 0xffffffff) >>> 0; +} + +/** A bundle member path: renderer/... or client/..., plain relative segments only. */ +export function bundlePath(name) { + if (typeof name !== 'string' || name.length > 512 || !/^(renderer|client)\/[A-Za-z0-9._@+~/-]+$/.test(name)) return null; + return name.split('/').every(part => part && part !== '.' && part !== '..') ? name : null; +} + +/** Reads the bundle ZIP: stored or deflated entries, no encryption, no ZIP64, every CRC checked. */ +export function readBundleZip(bytes) { + check(Buffer.isBuffer(bytes) && bytes.length >= 22 && bytes.length <= MAX_BUNDLE_BYTES, 400, '网页版界面包大小无效'); + let end = -1; + for (let at = bytes.length - 22; at >= Math.max(0, bytes.length - 65557); at--) + if (bytes.readUInt32LE(at) === 0x06054b50 && at + 22 + bytes.readUInt16LE(at + 20) === bytes.length) { end = at; break; } + check(end >= 0 && bytes.readUInt16LE(end + 4) === 0 && bytes.readUInt16LE(end + 6) === 0, 400, '不是网页版界面包(ZIP 目录无效)'); + const count = bytes.readUInt16LE(end + 10), size = bytes.readUInt32LE(end + 12), start = bytes.readUInt32LE(end + 16); + check(count > 1 && count <= MAX_FILES + 1 && count === bytes.readUInt16LE(end + 8) && start + size === end, 400, '网页版界面包目录无效'); + const files = new Map(); + let cursor = start, total = 0, previousEnd = 0; + for (let index = 0; index < count; index++) { + check(cursor + 46 <= end && bytes.readUInt32LE(cursor) === 0x02014b50, 400, '网页版界面包条目无效'); + const flags = bytes.readUInt16LE(cursor + 8), method = bytes.readUInt16LE(cursor + 10); + const crc = bytes.readUInt32LE(cursor + 16), compressed = bytes.readUInt32LE(cursor + 20), expanded = bytes.readUInt32LE(cursor + 24); + const nameSize = bytes.readUInt16LE(cursor + 28), extraSize = bytes.readUInt16LE(cursor + 30), commentSize = bytes.readUInt16LE(cursor + 32); + const offset = bytes.readUInt32LE(cursor + 42); + check(!(flags & ~0x800) && [0, 8].includes(method) && expanded <= MAX_FILE_BYTES && (total += expanded) <= MAX_TOTAL_BYTES, + 400, '网页版界面包含不支持的条目'); + const name = bytes.subarray(cursor + 46, cursor + 46 + nameSize).toString('utf8'); + check(name === 'web-bundle.json' || bundlePath(name), 400, `网页版界面包路径无效:${name.slice(0, 120)}`); + check(!files.has(name), 400, `网页版界面包路径重复:${name.slice(0, 120)}`); + // Entries must follow each other without overlapping, before the central directory. + check(offset >= previousEnd && offset + 30 <= start && bytes.readUInt32LE(offset) === 0x04034b50, 400, '网页版界面包条目位置无效'); + const data = offset + 30 + bytes.readUInt16LE(offset + 26) + bytes.readUInt16LE(offset + 28); + check(data + compressed <= start && bytes.subarray(offset + 30, offset + 30 + nameSize).toString('utf8') === name, 400, '网页版界面包条目无效'); + previousEnd = data + compressed; + let content; + try { + content = method === 0 ? bytes.subarray(data, data + compressed) + : inflateRawSync(bytes.subarray(data, data + compressed), { maxOutputLength: Math.max(1, expanded) }); + } catch { check(false, 400, `网页版界面包解压失败:${name.slice(0, 120)}`); } + check(content.length === expanded && crc32(content) === crc, 400, `网页版界面包校验失败:${name.slice(0, 120)}`); + files.set(name, Buffer.from(content)); + cursor += 46 + nameSize + extraSize + commentSize; + } + check(cursor === end, 400, '网页版界面包目录无效'); + return files; +} + +/** Checks the manifest against the files: same set of paths, sizes and SHA-256. */ +export function verifyBundle(entries) { + const raw = entries.get('web-bundle.json'); + check(raw, 400, '缺少 web-bundle.json,请用 web/patchers/patch.mjs 生成网页版界面包'); + let manifest; + try { manifest = JSON.parse(raw.toString('utf8')); } catch { check(false, 400, 'web-bundle.json 格式错误'); } + check(manifest?.schema === BUNDLE_SCHEMA, 400, '网页版界面包格式不受支持,请用同一版本的工具重新生成'); + check(/^\d+\.\d+\.\d+$/.test(manifest.rendererVersion ?? ''), 400, '网页版界面包的版本无效'); + check(manifest.files && typeof manifest.files === 'object' && !Array.isArray(manifest.files), 400, 'web-bundle.json 缺少文件清单'); + const listed = Object.keys(manifest.files); + check(listed.length === entries.size - 1, 400, '网页版界面包的文件与清单不一致'); + for (const name of listed) { + const bytes = entries.get(name), item = manifest.files[name]; + check(bundlePath(name) && bytes && item?.bytes === bytes.length && item.sha256 === sha256(bytes), 400, `网页版界面包文件与清单不一致:${name.slice(0, 120)}`); + } + for (const name of REQUIRED) check(Object.hasOwn(manifest.files, name), 400, `网页版界面包缺少 ${name}`); + return manifest; +} + +export class WebClient { + constructor(dataDir, { auth } = {}) { + this.root = join(dataDir, 'web-client'); + this.auth = auth; + this.store = new JsonStore(join(dataDir, 'web-client.json'), { version: 1, enabled: false, installedAt: null }); + this.index = null; + this.manifest = null; + this.installing = Promise.resolve(); + } + async load() { + await this.store.load(); + // An upload interrupted by a restart leaves its stage or the replaced bundle behind. + const leftovers = await readdir(this.root).catch(error => { if (error.code === 'ENOENT') return []; throw error; }); + for (const name of leftovers.filter(name => /^(stage|previous)-[0-9a-f]{12}$/.test(name))) + await rm(join(this.root, name), { recursive: true, force: true }); + await this.readCurrent(); + return this; + } + async readCurrent() { + this.index = null; this.manifest = null; + let manifest; + try { manifest = JSON.parse(await readFile(join(this.root, 'current', 'web-bundle.json'), 'utf8')); } + catch (error) { + if (error.code === 'ENOENT') return; + console.error(`[web-client] installed bundle unreadable: ${error.code ?? error.name}`); + return; + } + if (manifest?.schema !== BUNDLE_SCHEMA || !manifest.files) return; + this.manifest = manifest; + this.index = new Map(Object.entries(manifest.files).filter(([name]) => bundlePath(name))); + } + get installed() { return Boolean(this.index); } + get available() { return this.installed && this.store.value.enabled === true; } + status() { + const manifest = this.manifest; + return { + installed: this.installed, enabled: this.store.value.enabled === true, available: this.available, + installedAt: this.installed ? this.store.value.installedAt : null, + rendererVersion: manifest?.rendererVersion ?? null, recommended: manifest?.recommended ?? null, builtAt: manifest?.builtAt ?? null, + files: this.index?.size ?? 0, bytes: [...(this.index?.values() ?? [])].reduce((sum, item) => sum + (item.bytes ?? 0), 0), + }; + } + install(bytes) { + const work = this.installing.then(() => this.replace(bytes)); + this.installing = work.catch(() => {}); + return work; + } + async replace(bytes) { + const entries = readBundleZip(bytes); + const manifest = verifyBundle(entries); + entries.delete('web-bundle.json'); + await mkdir(this.root, { recursive: true, mode: 0o700 }); + const suffix = randomBytes(6).toString('hex'); + const stage = join(this.root, `stage-${suffix}`), previous = join(this.root, `previous-${suffix}`), current = join(this.root, 'current'); + try { + for (const [name, content] of entries) { + const target = join(stage, ...name.split('/')); + await mkdir(dirname(target), { recursive: true }); + await writeFile(target, content); + // Compressed once here, so each request only streams a file. + if (COMPRESSIBLE.has(extension(name)) && content.length >= 1024) { + const packed = await gzip(content, { level: 9 }); + if (packed.length < content.length) { await writeFile(`${target}.gz`, packed); manifest.files[name].gzip = true; } + } + } + await writeFile(join(stage, 'web-bundle.json'), JSON.stringify(manifest)); + let replaced = false; + try { await rename(current, previous); replaced = true; } catch (error) { if (error.code !== 'ENOENT') throw error; } + try { await rename(stage, current); } + catch (error) { if (replaced) await rename(previous, current).catch(() => {}); throw error; } + } finally { + await rm(stage, { recursive: true, force: true }); + await rm(previous, { recursive: true, force: true }); + } + // The first installation turns the web client on; a later one keeps the administrator's choice. + await this.store.mutate(state => { + if (!state.installedAt) state.enabled = true; + state.installedAt = new Date().toISOString(); + }); + await this.readCurrent(); + return this.status(); + } + async setEnabled(enabled) { + check(typeof enabled === 'boolean', 400, '启用状态无效'); + check(!enabled || this.installed, 409, '请先上传网页版界面包'); + await this.store.mutate(state => { state.enabled = enabled; }); + return this.status(); + } + async remove() { + await this.installing; + this.index = null; this.manifest = null; + await rm(join(this.root, 'current'), { recursive: true, force: true }); + await this.store.mutate(state => { state.enabled = false; state.installedAt = null; }); + return this.status(); + } + + // ---- sign-in ------------------------------------------------------------------------------- + + sessionCookie(token, origin) { + return `${WEB_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${token ? COOKIE_SECONDS : 0}${origin.startsWith('https:') ? '; Secure' : ''}`; + } + /** The browser device signed in on this request, from its cookie; null when there is none. */ + browserDevice(request) { + const token = cookie(request, WEB_COOKIE); + if (!this.available || !token || !/^[A-Za-z0-9_-]{32,256}$/.test(token)) return null; + const device = this.auth.authenticate(token); + return device?.platform === 'web' ? { device, token } : null; + } + /** + * The device token for a device API request from the web client, or null when the request + * does not use the browser cookie. A cookie without the header or from another origin is refused. + */ + deviceToken(request, origin) { + if (request.headers.authorization !== undefined) return null; + const token = cookie(request, WEB_COOKIE); + if (!token) return null; + check(this.available, 403, '网页版未启用'); + check(request.headers['x-grokbot-web'] === '1', 403, '请从网页版发起请求'); + check(!request.headers.origin || request.headers.origin === origin, 403, '请求来源不匹配'); + return token; + } + + // ---- files --------------------------------------------------------------------------------- + + has(name) { return Boolean(this.index?.has(name)); } + /** Streams one bundle file; the caller has checked the browser's sign-in. */ + async serve(request, response, name) { + const item = this.index?.get(name); + check(item, 404, '文件不存在'); + const etag = `"${item.sha256.slice(0, 40)}"`; + // Hashed asset names never change content; everything else is revalidated. + response.setHeader('cache-control', /^renderer\/assets\//.test(name) ? 'private, max-age=31536000, immutable' : 'private, no-cache'); + response.setHeader('etag', etag); + response.setHeader('cross-origin-resource-policy', 'same-origin'); + response.setHeader('vary', 'Accept-Encoding, Cookie'); + if (request.headers['if-none-match'] === etag) { response.writeHead(304); return response.end(); } + const packed = item.gzip && /\bgzip\b/.test(String(request.headers['accept-encoding'] ?? '')); + const file = join(this.root, 'current', ...name.split('/')) + (packed ? '.gz' : ''); + const headers = { 'content-type': TYPES[extension(name)] ?? 'application/octet-stream', ...(packed ? { 'content-encoding': 'gzip' } : {}) }; + if (request.method === 'HEAD') { response.writeHead(200, headers); return response.end(); } + await new Promise((resolve, reject) => { + const stream = createReadStream(file); + stream.once('open', () => { response.writeHead(200, headers); stream.pipe(response); }); + stream.once('error', reject); + stream.once('end', resolve); + response.once('close', () => { stream.destroy(); resolve(); }); + }); + } + /** The scripts the Bot computer view loads beside the noVNC page (see android/client/vnc-bridge.js). */ + async vncScript(name, origin) { + const file = name === 'vnc-bridge' ? 'client/vnc-bridge.js' : 'client/vnc-preload.js'; + check(this.has(file), 404, '文件不存在'); + const script = await readFile(join(this.root, 'current', ...file.split('/'))); + return name === 'vnc-bridge' ? Buffer.concat([Buffer.from(`window.__grokbotAppOrigin = ${JSON.stringify(origin)};\n`), script]) : script; + } + /** Adds the bridge scripts to the noVNC page right after , in the page's own directory. */ + static injectVncBridge(html, directory) { + const tags = ``; + const opening = /]*)?>/i.exec(html); + return opening ? html.slice(0, opening.index + opening[0].length) + tags + html.slice(opening.index + opening[0].length) : tags + html; + } +} + +/** Reads a raw request body up to `limit` bytes. */ +export async function rawBody(request, limit = MAX_BUNDLE_BYTES) { + const length = Number(request.headers['content-length'] ?? NaN); + check(!Number.isFinite(length) || length <= limit, 413, '网页版界面包过大'); + const chunks = []; + let size = 0; + for await (const chunk of request) { + size += chunk.length; + check(size <= limit, 413, '网页版界面包过大'); + chunks.push(chunk); + } + return Buffer.concat(chunks, size); +} + +/** The installable-app description for phones; it names the Host, never the interface's files. */ +export function webManifest() { + return { + name: 'Grok Bot', short_name: 'Grok Bot', start_url: '/web/', scope: '/web/', display: 'standalone', + background_color: '#111111', theme_color: '#111111', + icons: [{ src: '/web/client/icon.png', sizes: '256x256', type: 'image/png', purpose: 'any' }], + }; +} diff --git a/host/source-files.json b/host/source-files.json deleted file mode 100644 index 466bc23e0700d4f803b288fe2f00cdda9c97610b..0000000000000000000000000000000000000000 --- a/host/source-files.json +++ /dev/null @@ -1,190 +0,0 @@ -[ - "clients/shared/notification-frequency.mjs", - "clients/shared/tailcat-process.mjs", - "deploy/credentials.mjs", - "deploy/execution-gateway.mjs", - "deploy/execution-tailcat.mjs", - "deploy/healthcheck.mjs", - "deploy/host-supervisor.mjs", - "deploy/supervisor.mjs", - "runtime/box-applications.mjs", - "runtime/codex-prompt.mjs", - "runtime/config.mjs", - "runtime/context-policy.mjs", - "runtime/federation-task-bridge.mjs", - "runtime/host-attachments.mjs", - "runtime/host-auto-review.mjs", - "runtime/host-automations.mjs", - "runtime/host-capabilities.mjs", - "runtime/host-computers.mjs", - "runtime/host-extensions.mjs", - "runtime/host-federation.mjs", - "runtime/host-library-files.mjs", - "runtime/host-local-profile.mjs", - "runtime/host-mcp-remote.mjs", - "runtime/host-mcp.mjs", - "runtime/host-network.mjs", - "runtime/host-notifications.mjs", - "runtime/host-skills.mjs", - "runtime/host-speech.mjs", - "runtime/host-teach.mjs", - "runtime/host-webhooks.mjs", - "runtime/host.mjs", - "runtime/media-client.mjs", - "runtime/media-runtime.mjs", - "runtime/media-services.mjs", - "runtime/media-video-session.mjs", - "runtime/model-errors.mjs", - "runtime/model-observation.mjs", - "runtime/model-policy.mjs", - "runtime/model-router.mjs", - "runtime/model-session.mjs", - "runtime/native-desktop.mjs", - "runtime/native-mcp.mjs", - "runtime/prompt-runtime.mjs", - "runtime/recovered-blob-worker.mjs", - "runtime/recovered-computer.mjs", - "runtime/recovered-engine.mjs", - "runtime/recovered-harness.mjs", - "runtime/recovered-host-core.mjs", - "runtime/recovered-host-execution.mjs", - "runtime/recovered-host-flow.mjs", - "runtime/recovered-host-kernel.mjs", - "runtime/recovered-modules.mjs", - "runtime/recovered-prompt-tools.mjs", - "runtime/recovered-storage.mjs", - "runtime/recovered-tool-framework.mjs", - "runtime/recovered-worker-pool.mjs", - "runtime/reliability/handoff-store.mjs", - "runtime/reliability/tool-journal.mjs", - "runtime/remote-box.mjs", - "runtime/reply-notifier.mjs", - "runtime/routing-log.mjs", - "runtime/sharing-client.mjs", - "runtime/sharing-import.mjs", - "runtime/skill-files.mjs", - "runtime/teach-skill/SKILL.md", - "runtime/teach-skill/prepare.py", - "runtime/usage-ledger.mjs", - "runtime/web-services.mjs", - "server/admin-extensions.mjs", - "server/application-guide.md", - "server/applications-api.mjs", - "server/applications.mjs", - "server/attachments.mjs", - "server/auth.mjs", - "server/avatar.mjs", - "server/connectors-mcp.mjs", - "server/connectors-mobile.mjs", - "server/connectors-oauth.mjs", - "server/connectors-store.mjs", - "server/connectors.mjs", - "server/desktop-browser.mjs", - "server/desktop-capabilities.mjs", - "server/execution-node.mjs", - "server/federation-api.mjs", - "server/federation-identity.mjs", - "server/federation-queue.mjs", - "server/federation-tasks.mjs", - "server/federation.mjs", - "server/harness-settings.mjs", - "server/host-api.mjs", - "server/index.mjs", - "server/internal-host.mjs", - "server/library.mjs", - "server/local-exec-proxy.mjs", - "server/media-api.mjs", - "server/media-http.mjs", - "server/media-internal.mjs", - "server/media-providers.mjs", - "server/media-settings.mjs", - "server/mobile-app-intents.mjs", - "server/models.mjs", - "server/notification-settings.mjs", - "server/notifications.mjs", - "server/package-files.mjs", - "server/package-lock.json", - "server/package.json", - "server/plugin-client.mjs", - "server/plugin-package.mjs", - "server/plugins-api.mjs", - "server/plugins.mjs", - "server/profile.mjs", - "server/prompt-api.mjs", - "server/prompt-settings.mjs", - "server/proxy.mjs", - "server/public/app-package.js", - "server/public/app.js", - "server/public/apps.js", - "server/public/base.css", - "server/public/components.css", - "server/public/connector-form.js", - "server/public/connector-result.css", - "server/public/connector-result.html", - "server/public/connector-result.js", - "server/public/crew.js", - "server/public/devices.js", - "server/public/execution.js", - "server/public/face.js", - "server/public/favicon.svg", - "server/public/federation.js", - "server/public/general.js", - "server/public/harness.js", - "server/public/i18n.js", - "server/public/icons.js", - "server/public/index.html", - "server/public/locales-en.js", - "server/public/login.js", - "server/public/media-editor-ui.js", - "server/public/media-web.js", - "server/public/media.js", - "server/public/model.js", - "server/public/navigation.js", - "server/public/network.js", - "server/public/notifications.js", - "server/public/overview.js", - "server/public/pages.css", - "server/public/privacy.js", - "server/public/prompt-diff.js", - "server/public/prompts.js", - "server/public/push.js", - "server/public/routing-log.js", - "server/public/sharing.js", - "server/public/shell.css", - "server/public/skills.js", - "server/public/speech.js", - "server/public/stage.css", - "server/public/theme.js", - "server/public/tokens.css", - "server/public/ui.js", - "server/public/voice.js", - "server/public/webhooks.js", - "server/push-config.mjs", - "server/push-service.mjs", - "server/push-transports.mjs", - "server/security.mjs", - "server/sharing-api.mjs", - "server/sharing-package.mjs", - "server/sharing-zip.mjs", - "server/sharing.mjs", - "server/skills.mjs", - "server/speech-audio.mjs", - "server/speech-providers.mjs", - "server/speech.mjs", - "server/storage.mjs", - "server/tailcat-ingress.mjs", - "server/tailcat.mjs", - "server/vnc.mjs", - "server/voice-audio.mjs", - "server/voice-catalog.mjs", - "server/voice-config.mjs", - "server/voice-host.mjs", - "server/voice-onset.mjs", - "server/voice-playback.mjs", - "server/voice-session.mjs", - "server/voice-synthesis.mjs", - "server/voice.mjs", - "server/web-settings.mjs", - "server/webhooks-api.mjs", - "server/webhooks.mjs" -] diff --git a/host/tests/admin-ui-browser.py b/host/tests/admin-ui-browser.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf581684519a56ccb6b469318a267a94b3d06a --- /dev/null +++ b/host/tests/admin-ui-browser.py @@ -0,0 +1,354 @@ +"""Optional Chromium checks: python -B host/tests/admin-ui-browser.py [--artifacts DIR]. + +Only public assets are served on loopback. Every API response is a demo fixture; +other origins are blocked. No Host, saved browser profile or credentials needed. +""" +import argparse +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import re +from threading import Thread +import unittest +from urllib.parse import urlsplit + +from playwright.sync_api import expect, sync_playwright + + +PUBLIC = Path(__file__).resolve().parents[1] / 'server' / 'public' +FORMATS = ['OpenAI Chat Completions', 'OpenAI Responses', 'Anthropic Messages'] +HTML = 'DEMO PROXYDemo proxy page' +ARTIFACTS = None + + +class Static(SimpleHTTPRequestHandler): + def log_message(self, *args): + pass + + +class AdminUI(unittest.TestCase): + @classmethod + def setUpClass(cls): + http = ThreadingHTTPServer(('127.0.0.1', 0), partial(Static, directory=PUBLIC)) + cls.origin = 'http://127.0.0.1:' + str(http.server_port) + thread = Thread(target=http.serve_forever, daemon=True) + thread.start() + cls.addClassCleanup(http.server_close) + cls.addClassCleanup(thread.join) + cls.addClassCleanup(http.shutdown) + driver = sync_playwright().start() + cls.addClassCleanup(driver.stop) + chrome = Path('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome') + cls.browser = driver.chromium.launch(executable_path=str(chrome), + args=['--disable-background-networking']) if chrome.exists() else driver.chromium.launch( + args=['--disable-background-networking']) + cls.addClassCleanup(cls.browser.close) + + def start(self, view='overview', *, mobile=False, locale='en-US', initial='ready', authenticated=True, demo_bot=False, + legacy=None): + self.mode, self.authenticated, self.reply = initial, authenticated, 'ok' + self.demo_bot, self.legacy, self.saved = demo_bot, legacy, None + self.requests, self.unexpected = [], [] + viewport = {'width': 390, 'height': 844} if mobile else {'width': 1440, 'height': 940} if view == 'model' else {'width': 1280, 'height': 900} + context = self.browser.new_context(locale=locale, timezone_id='UTC', + viewport=viewport, + is_mobile=mobile, has_touch=mobile, reduced_motion='reduce', service_workers='block') + self.addCleanup(context.close) + self.addCleanup(lambda: self.assertEqual(self.unexpected, [])) + context.route('**/*', self.route) + self.page = context.new_page() + self.page.on('pageerror', lambda error: self.unexpected.append(str(error))) + self.page.clock.install() + self.page.goto(self.origin + '/?view=' + view, wait_until='networkidle') + return self.page + + def route(self, route): + req = route.request + parts = urlsplit(req.url) + if parts.scheme + '://' + parts.netloc != self.origin: + self.unexpected.append('off-origin request: ' + parts.netloc) + return route.abort() + if not parts.path.startswith('/admin/api/'): + return route.continue_() + key = parts.path.removeprefix('/admin/api/') + self.requests.append((req.method, key)) + if key == 'session': + return route.fulfill(json={'initialized': True, 'authenticated': self.authenticated}) + if key == 'login' and self.reply == 'ok': + self.authenticated = True + return route.fulfill(json={'ok': True}) + mode = self.mode if key == 'status' else self.reply if key in ('login', 'model/test', 'voice/test') else None + if mode == 'dropped': + return route.abort('connectionreset') + if mode == 'stalled': + self.stalled = route + return + if mode in ('401', '502'): + return route.fulfill(status=int(mode), content_type='text/html', body=HTML) + if mode == 'json401': + return route.fulfill(status=401, json={'error': '管理员密码不正确' if key == 'login' else '请登录管理页面'}) + configured = self.mode != 'unconfigured' + model = { + 'version': 1, + 'providers': [ + {'id': 'demo', 'name': 'Demo service', 'apiFormat': 'openai', + 'baseUrl': 'https://model.example.invalid/v1', 'hasApiKey': configured}, + {'id': 'backup', 'name': 'Backup service', 'apiFormat': 'anthropic', + 'baseUrl': 'https://backup.example.invalid', 'hasApiKey': configured}, + ] if configured else [], + 'profiles': [ + {'id': 'primary', 'name': 'Primary profile', 'providerId': 'demo', 'model': 'demo-model', + 'efforts': ['low'], 'contextWindowTokens': 0, 'summaryThresholdTokens': 0}, + {'id': 'backup', 'name': 'Backup profile', 'providerId': 'backup', 'model': 'demo-backup', + 'efforts': ['high'], 'contextWindowTokens': 0, 'summaryThresholdTokens': 0}, + ] if configured else [], + 'defaultRoute': {'profileId': 'primary', 'effort': 'low', + 'fallbacks': [{'profileId': 'backup', 'effort': 'high'}]} if configured else None, + 'botRoutes': {'demo-bot': {'profileId': 'backup', 'effort': 'high', + 'fallbacks': [{'profileId': 'primary', 'effort': 'low'}]}} + if configured and self.demo_bot else {}, + 'model': 'demo-model' if configured else '', + 'configured': configured, 'reload': {'status': 'applied'}, 'hasApiKey': configured, + 'routingMigrated': self.legacy is not None, 'legacyAdaptiveRouting': self.legacy == 'adaptive', + } + if key == 'model' and req.method == 'PUT': + self.saved, self.legacy = req.post_data_json, None + model.update(routingMigrated=False, legacyAdaptiveRouting=False) + fixtures = {'status': {'model': model, 'devices': [], 'pairingKeys': [], 'notifications': {}, + 'publicUrl': 'https://demo.example.invalid', + 'host': {'connected': self.mode == 'ready', 'busy': False, + 'agents': [{'id': 'demo-bot', 'name': 'Research Bot', 'isRunning': False, + 'isGroup': False}] if configured and self.demo_bot else [], + 'waitingForExecutionNode': self.mode == 'split-wait'}}, + 'profile': {'displayName': 'Demo workspace', 'hostName': 'Demo Host', 'avatarDataUrl': None}, + 'usage': {'requests': 0}, 'speech': {'enabled': False, 'provider': 'fish'}, + 'voice': {'enabled': True, 'asr': {'configured': False}, 'tts': {'provider': 'openai', + 'endpoint': 'https://voice.example.invalid', 'model': 'demo', 'voice': 'demo', 'speed': 1}}, + 'media': {'defaults': {}}, 'web-services': {'defaults': {}}, 'harness': {}, 'skills': [], + 'apps': {'apps': []}, 'network': {'enabled': False}, 'execution': {'enabled': False, 'url': '', 'name': 'Demo node'}, + 'federation': {'peers': []}, 'webhooks': [], 'sharing': [], + 'model/routing-log': {'items': []}, 'model': model} + if key not in fixtures: + self.unexpected.append('unexpected demo API: ' + key) + return route.fulfill(status=404, json={'error': 'Unknown demo endpoint'}) + return route.fulfill(json=fixtures[key]) + + def poll(self, mode): + self.mode = mode + event = 'requestfailed' if mode == 'dropped' else 'response' + with self.page.expect_event(event, predicate=lambda r: r.url.endswith('/admin/api/status')): + self.page.clock.fast_forward(5000) + self.page.wait_for_load_state('networkidle') + + def capture(self, name, **data): + if ARTIFACTS: + self.page.screenshot(path=ARTIFACTS / (name + '.png'), animations='disabled') + (ARTIFACTS / (name + '.json')).write_text(json.dumps({**data, 'requests': self.requests}, + ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + + def test_split_wait_points_to_the_real_execution_editor(self): + page = self.start(mobile=True, initial='split-wait') + expect(page.locator('#header-health')).to_have_text('Execution node required') + action = page.locator('#attention-list button[data-view=execution]') + expect(action).to_have_text('Set up node') + self.capture('split-wait', action=action.inner_text()) + action.click() + expect(page.locator('#execution-form')).to_be_visible() + self.assertIn(('GET', 'execution'), self.requests) + + def test_status_loss_and_recovery(self): + page = self.start() + header, hero = page.locator('#header-health'), page.locator('#hero-title') + expect(header).to_have_text('Host ready') + self.poll('core-down') + expect(header).to_have_text('Waiting for Host') + self.poll('ready') + for mode in ['dropped', '502']: + with self.subTest(mode=mode): + self.poll(mode) + self.capture('status-' + mode, header=header.inner_text(), tone=header.get_attribute('data-tone'), + headline=hero.inner_text()) + self.assertNotEqual(header.get_attribute('data-tone'), 'success') + self.assertEqual(header.inner_text(), 'Status unavailable') + self.assertEqual(hero.inner_text(), 'Status unavailable') + expect(page.locator('#hero-host')).to_be_hidden() + if mode == '502': + expect(page.locator('.hero-copy')).to_contain_text('502') + expect(page.locator('body')).not_to_contain_text('DEMO PROXY') + self.poll('ready') + expect(hero).to_have_text('Host ready') + expect(header).to_have_attribute('data-tone', 'success') + + def test_offline_and_stalled_poll(self): + page = self.start() + header = page.locator('#header-health') + expect(header).to_have_text('Host ready') + self.mode = 'dropped' + page.context.set_offline(True) + expect(header).to_have_text('Status unavailable', timeout=1500) + self.mode = 'ready' + page.context.set_offline(False) + expect(header).to_have_text('Host ready', timeout=2000) + self.mode = 'stalled' + with page.expect_request(lambda r: r.url.endswith('/admin/api/status')): + page.clock.fast_forward(5000) + page.clock.run_for(12050) + expect(header).to_have_text('Status unavailable') + expect(page.locator('#hero-status-error')).to_have_text('Host status request timed out.') + self.stalled.abort() + self.poll('ready') + expect(header).to_have_text('Host ready') + + def test_first_status_expired(self): + page = self.start(view='model', initial='json401') + expect(page.locator('#auth-screen')).to_be_visible() + first = len(self.requests) + for _ in range(2): + page.clock.fast_forward(5000) + page.wait_for_load_state('networkidle') + self.capture('first-status-expired', notice=page.locator('#auth-error').text_content(), + extra_requests=len(self.requests) - first) + self.assertEqual(self.requests, [('GET', 'session'), ('GET', 'status')]) + expect(page.locator('#auth-error')).to_have_text('Session expired. Sign in again.') + expect(page.locator('#auth-password')).to_be_focused() + self.mode = 'ready' + page.keyboard.type('demo-password-only') + page.keyboard.press('Enter') + expect(page.locator('#header-health')).to_have_text('Host ready') + self.poll('core-down') + expect(page.locator('#header-health')).to_have_text('Waiting for Host') + + def test_proxy_expiry_during_poll(self): + page = self.start() + self.poll('401') + first = len(self.requests) + page.clock.fast_forward(10000) + page.wait_for_load_state('networkidle') + self.capture('poll-html-401', notice=page.locator('#auth-error').text_content(), + auth_visible=page.locator('#auth-screen').is_visible(), extra_requests=len(self.requests) - first) + self.assertEqual(self.requests[first:], []) + expect(page.locator('#auth-error')).to_have_text('Session expired. Sign in again.') + expect(page.locator('#console')).to_be_hidden() + + def test_login_proxy_and_json_errors(self): + page = self.start(authenticated=False) + field = page.get_by_label('Admin password', exact=True) + for reply, message in [('401', '401'), ('502', '502'), ('json401', 'Incorrect administrator password')]: + with self.subTest(reply=reply): + self.reply = reply + field.fill('demo-password-only') + with page.expect_event('requestfinished', predicate=lambda r: r.url.endswith('/admin/api/login')): + field.press('Enter') + alert = page.locator('#auth-error') + expect(alert).to_be_visible() + self.capture('login-' + reply, notice=alert.inner_text()) + self.assertIn(message, alert.inner_text()) + self.assertNotRegex(alert.inner_text(), r'(?i) { + const range = document.createRange(); + const right = Math.max(...[...document.querySelectorAll('#hero-title span')].map(line => { + range.selectNodeContents(line); return range.getBoundingClientRect().right; + })); + return {textRight: right, iconLeft: document.querySelector('#hero-host').getBoundingClientRect().left}; + }''') + self.capture('mobile-setup', hint=hint, layout=layout) + self.assertLessEqual(layout['textRight'], layout['iconLeft']) + menu = page.get_by_role('button', name='Menu', exact=True) + page.keyboard.press('Tab') # brand link + page.keyboard.press('Tab') + expect(menu).to_be_focused() + page.keyboard.press('Space') + expect(menu).to_have_attribute('aria-expanded', 'true') + page.keyboard.press('Tab') # Overview + page.keyboard.press('Tab') + link = page.locator('#nav [data-view=model]') + expect(link).to_be_focused() + page.keyboard.press('Enter') + expect(link).to_have_attribute('aria-current', 'page') + expect(menu).to_have_attribute('aria-expanded', 'false') + expect(page.locator('#model-providers .item')).to_have_count(2) + expect(page.locator('#model-profiles .item')).to_have_count(2) + expect(page.locator('#model-default-route')).to_contain_text('Primary profile') + expect(page.locator('#model-default-route')).to_contain_text('Backup profile') + expect(page.locator('#model-bot-routes')).to_contain_text('Research Bot') + page.get_by_role('button', name='More actions for Demo service').click() + page.get_by_role('menuitem', name='Edit').click() + select = page.get_by_role('combobox', name='API format') + self.assertEqual(select.locator('option').all_text_contents(), FORMATS) + select.focus() + page.keyboard.press('ArrowDown') + expect(select).to_have_value('openai-responses') + page.keyboard.press('End') + expect(select).to_have_value('anthropic') + page.get_by_role('button', name='Cancel').last.click() + self.reply = '502' + page.get_by_role('button', name='Test connection').first.click() + toast = page.locator('#toast') + expect(toast).to_be_visible() + self.capture('mobile-model-error', notice=toast.inner_text(), format='openai') + self.assertEqual(toast.inner_text(), 'Request failed (502)') + page.goto(self.origin + '/?view=overview', wait_until='networkidle') + self.assertIn('Primary profile', page.locator('#model-default-route').inner_text()) + self.assertIn('Backup profile', page.locator('#model-default-route').inner_text()) + self.assertTrue(page.evaluate('document.documentElement.scrollWidth <= innerWidth')) + + def test_desktop_model_page_documents_routes(self): + page = self.start(view='model', demo_bot=True) + expect(page.locator('#model-providers .item')).to_have_count(2) + expect(page.locator('#model-profiles .item')).to_have_count(2) + expect(page.locator('#model-default-route')).to_contain_text('Primary profile') + expect(page.locator('#model-default-route')).to_contain_text('Backup profile') + expect(page.locator('#model-bot-routes')).to_contain_text('Research Bot') + expect(page.locator('#model-bot-routes')).to_contain_text('Backup profile') + self.capture('admin-model') + + def test_legacy_model_migration_mentions_jev_only_for_adaptive_routing(self): + for legacy in ('single', 'adaptive'): + with self.subTest(legacy=legacy): + page = self.start(view='model', legacy=legacy) + notice = page.locator('#legacy-routing-notice') + expect(notice).to_be_visible() + self.assertEqual('Jev' in notice.inner_text(), legacy == 'adaptive') + page.locator('#model-form button[type=submit]').click() + if legacy == 'adaptive': + confirm = page.locator('#confirm-dialog') + expect(confirm).to_contain_text('Jev') + confirm.locator('#confirm-accept').click() + expect(notice).to_be_hidden() + self.assertIs(self.saved.get('migrateLegacyRouting'), True) + + def test_chinese_setup_copy(self): + page = self.start(initial='unconfigured', locale='zh-CN') + hint = page.locator('#attention-list .row-hint').first.inner_text() + self.capture('zh-setup', hint=hint) + self.assertTrue(all(label in hint for label in FORMATS)) + + def test_voice_proxy_errors(self): + page = self.start(view='speech') + button, error = page.locator('#voice-preview'), page.locator('#voice-error') + self.reply = '502' + button.press('Enter') + expect(error).to_be_visible() + self.capture('voice-502', notice=error.inner_text()) + with self.subTest(status=502): + self.assertEqual(error.inner_text(), 'Request failed (502)') + self.reply = '401' + with page.expect_response(lambda r: r.url.endswith('/admin/api/voice/test')): + button.press('Enter') + expect(page.locator('#auth-error')).to_have_text('Session expired. Sign in again.') + expect(page.locator('#console')).to_be_hidden() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--artifacts', type=Path) + args, rest = parser.parse_known_args() + ARTIFACTS = args.artifacts + if ARTIFACTS: + ARTIFACTS.mkdir(parents=True, exist_ok=True) + unittest.main(argv=[__file__, *rest], verbosity=2) diff --git a/host/tests/admin-ui-cli.test.mjs b/host/tests/admin-ui-cli.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7a3cf4566aa4314190f6eb473635ad0a158dfdb5 --- /dev/null +++ b/host/tests/admin-ui-cli.test.mjs @@ -0,0 +1,100 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { createServer } from 'node:http'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +const exec = promisify(execFile); +const cli = fileURLToPath(new URL('../tools/host-admin.mjs', import.meta.url)); + +async function demo(t, reply = {}) { + const calls = []; + const server = createServer(async (req, res) => { + const path = req.url.slice('/admin/api/'.length); + let body = ''; + for await (const chunk of req) body += chunk; + calls.push({ method: req.method, path, body: body ? JSON.parse(body) : null }); + if (reply[path]) { + res.writeHead(reply[path], { 'content-type': 'text/html' }); + return res.end('DEMO PROXY'); + } + const fixture = { session: { initialized: true }, login: { ok: true }, setup: { ok: true }, + model: { model: 'demo', apiFormat: 'openai', baseUrl: 'https://model.example.invalid/v1' }, + 'model/catalog': { models: [{ id: 'demo', efforts: ['low', 'high'] }] }, 'model/test': { ok: true }, + status: { host: { connected: true }, model: { reload: { status: 'applied' } } }, 'pairing-keys': {} }; + res.writeHead(path in fixture ? 200 : 404, { 'content-type': 'application/json' }); + if (path === 'status' && reply.splitWait) fixture.status.host = { connected: false, waitingForExecutionNode: true }; + res.end(JSON.stringify(fixture[path] ?? { error: 'Unknown demo endpoint' })); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise(resolve => { server.close(resolve); server.closeAllConnections(); })); + const env = { ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), + GROKBOT_URL: `http://127.0.0.1:${server.address().port}`, GROKBOT_ADMIN_PASSWORD: 'demo-only-password', + GROKBOT_SETUP_KEY: 'demo-only', MODEL_API_KEY: 'demo-only' }; + const run = async args => { + calls.length = 0; + try { return { code: 0, ...await exec(process.execPath, [cli, ...args], { env, timeout: 8000 }) }; } + catch (error) { if (!Number.isInteger(error.code)) throw error; return error; } + }; + return { calls, run }; +} + +test('malformed admin options fail before login, tests or mutations', async t => { + const { calls, run } = await demo(t); + const set = ['model-set', '--model', 'demo']; + for (const args of [ + [...set, '--test-onyl', 'yes'], ['model-set', '--model', '--test-only'], [...set, '--context'], + [...set, '--context', 'not-a-number'], [...set, '--context', '1.5'], [...set, '--context', '100000001'], + [...set, '--format', 'chat'], [...set, '--effort', 'typo'], [...set, '--efforts', 'low,,high'], + [...set, '--efforts', 'low,typo'], [...set, '--efforts', 'low', '--effort', 'high'], + [...set, '--base-url', 'not-a-url'], [...set, '--model', 'other'], ['model-set', '--model', ' '], + [...set, '--test-only=false'], ['pair', '--test-only'], ['pair', '--model', 'demo'], + ['setup', '--bogus', 'value'], ['model-catalog', '--test-only'], + [...set, '--api-key-file', 'admin-ui-demo-missing-key'], + ]) await t.test(args.join(' '), async () => { + const result = await run(args); + assert.notEqual(result.code, 0, 'malformed invocation succeeded'); + assert.deepEqual(calls.map(({ method, path }) => `${method} ${path}`), [], 'must fail before any request'); + assert.match(result.stderr, /--[\w-]+/); + }); +}); + +test('valid model options test once; only a normal model-set saves', async t => { + const { calls, run } = await demo(t); + const args = ['model-set', '--model', 'demo', '--format', 'anthropic', '--effort', 'low', '--context', '0']; + const dry = await run([...args, '--test-only']); + assert.equal(dry.code, 0, dry.stderr); + assert.deepEqual(calls.map(call => call.path), ['login', 'model', 'model/catalog', 'model/test']); + assert.equal(calls.at(-1).body.apiFormat, 'anthropic'); + assert.equal(calls.at(-1).body.contextWindowTokens, 0); + assert.equal(calls.at(-1).body.policy.effort, 'low'); + const save = await run([...args, '--efforts', 'low,high']); + assert.equal(save.code, 0, save.stderr); + assert.deepEqual(calls.map(({ method, path }) => `${method} ${path}`), + ['POST login', 'GET model', 'POST model/test', 'PUT model', 'GET status']); +}); + +test('split setup reports a saved model waiting for its execution node immediately, without claiming application', async t => { + const { calls, run } = await demo(t, { splitWait: true }); + const result = await run(['model-set', '--model', 'demo', '--efforts', 'low']); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /执行节点/); + assert.doesNotMatch(result.stdout, /已应用/); + assert.deepEqual(calls.slice(-2).map(c => c.path), ['model', 'status']); +}); + +test('CLI never prints proxy pages or saves after a non-JSON model test', async t => { + const reply = {}, { calls, run } = await demo(t, reply); + for (const [path, status] of [['login', 401], ['model/test', 502], ['model/test', 200], ['model/test', 204]]) { + await t.test(`${path} HTTP ${status}`, async () => { + reply[path] = status; + const result = await run(['model-set', '--model', 'demo', '--efforts', 'low']); + delete reply[path]; + assert.notEqual(result.code, 0); + assert.match(result.stderr, status === 204 ? /未确认成功/ : new RegExp(`HTTP ${status}`)); + assert.doesNotMatch(result.stdout + result.stderr, / call.method === 'PUT')); + }); + } +}); diff --git a/host/tests/auto-review.test.mjs b/host/tests/auto-review.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..66a98e709c482da2c6de50677d76905309ee337e --- /dev/null +++ b/host/tests/auto-review.test.mjs @@ -0,0 +1,51 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createLocalClassifier } from '../runtime/host-auto-review.mjs'; + +const tool = { type: 'function', function: { name: 'classify', description: 'Classify the action', + parameters: { type: 'object', required: ['decision', 'reason', 'blocked_effect'], properties: { + decision: { type: 'string', enum: ['ALLOW', 'BLOCK'] }, reason: { type: 'string' }, + blocked_effect: { type: 'string', enum: ['none', 'destructive_local_change', 'outbound_or_binding_external_effect'] } } } } }; +const library = { CLASSIFY_SAND_AUTO_REVIEW_ACTION_TOOL: tool, SAND_AUTO_REVIEW_CLASSIFIER_SYSTEM_PROMPT: 'Review.', + SmartModeClassifierResult: class { constructor(value) { Object.assign(this, value); } } }; +const reply = content => new Response(JSON.stringify({ id: 'msg_1', model: 'm', stop_reason: 'end_turn', + usage: { input_tokens: 1, output_tokens: 1 }, content }), { status: 200, headers: { 'content-type': 'application/json' } }); +const textOnly = () => reply([{ type: 'text', text: 'Looks fine to me.' }]); +const valid = () => reply([{ type: 'tool_use', id: 't1', name: 'classify', + input: { decision: 'ALLOW', reason: 'Read-only command', blocked_effect: 'none' } }]); + +async function classifier(t, replies) { + const usageDirectory = await mkdtemp(join(tmpdir(), 'review-test-')); + t.after(() => rm(usageDirectory, { recursive: true, force: true })); + const logs = [], requests = []; + const instance = createLocalClassifier({ apiFormat: 'anthropic', baseUrl: 'https://api.example.com', apiKey: 'k', model: 'm', usageDirectory }, + library, { log: message => logs.push(message), fetchImpl: async (url, options) => { requests.push(url); return replies.shift()(); } }); + return { instance, logs, requests }; +} +const args = { target: { action: 'run', arguments: { command: 'ver' } }, conversationContext: [{ role: 'user', content: 'Check the version' }] }; + +test('a malformed classification is retried once and then succeeds', async t => { + const { instance, logs, requests } = await classifier(t, [textOnly, valid]); + const result = await instance.execute(undefined, args); + assert.equal(result.result.value.decision, 1); + assert.equal(requests.length, 2); + assert.match(logs[0], /retrying after: Auto-review model did not return one complete classification/); + assert.match(logs[1], /Local auto-review ALLOW/); +}); + +test('a second malformed classification fails and is logged', async t => { + const { instance, logs, requests } = await classifier(t, [textOnly, textOnly]); + await assert.rejects(instance.execute(undefined, args), /did not return one complete classification/); + assert.equal(requests.length, 2); + assert.match(logs.at(-1), /Local auto-review failed/); +}); + +test('service errors are not retried', async t => { + const { instance, logs, requests } = await classifier(t, [() => new Response('{"error":{"message":"overloaded"}}', { status: 529 })]); + await assert.rejects(instance.execute(undefined, args)); + assert.equal(requests.length, 1); + assert.match(logs.at(-1), /Local auto-review failed/); +}); diff --git a/host/tests/bytepatch.test.mjs b/host/tests/bytepatch.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1ac67afb50ffc04dd25940e7e2cff7208dcf2e4a --- /dev/null +++ b/host/tests/bytepatch.test.mjs @@ -0,0 +1,11 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +test('pinned Host patches reuse immutable inputs and verify every output', () => { + const run = spawnSync(process.platform === 'win32' ? 'python' : 'python3', + [fileURLToPath(new URL('bytepatch_checks.py', import.meta.url))], { encoding: 'utf8' }); + assert.ifError(run.error); + assert.equal(run.status, 0, run.stderr || run.stdout); +}); diff --git a/host/tests/bytepatch_checks.py b/host/tests/bytepatch_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2fe143ae067f4d901904425d96b593f9c20841 --- /dev/null +++ b/host/tests/bytepatch_checks.py @@ -0,0 +1,119 @@ +import hashlib +import io +import importlib.util +import json +import base64 +import os +from pathlib import Path +import sys +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'release')) +import bytepatch + +PATCH_HOST = Path(__file__).resolve().parents[1] / 'release' / 'patch-host.py' +PATCH_HOST_SPEC = importlib.util.spec_from_file_location('patch_host', PATCH_HOST) +patch_host = importlib.util.module_from_spec(PATCH_HOST_SPEC) +PATCH_HOST_SPEC.loader.exec_module(patch_host) + + +def pinned_host_archive(): + configured = os.environ.get('PROKBOT_TEST_HOST_ARCHIVE') + candidates = [Path(configured).expanduser()] if configured else [ + Path(__file__).resolve().parents[2] / 'inputs' / 'host' / 'sand-host-bundle-d0a4baa.tgz', + ] + for path in candidates: + if path.is_file() and bytepatch.file_digest(path) == 'b03894dc9a29eadc6ee1b7265424fe5695d77c5af0cdc022f27338cd69f73d0f': + with tarfile.open(path, 'r:gz') as archive: + member = archive.extractfile('sand-host/host-main.cjs') + if member is None: + raise ValueError('Pinned Host archive has no sand-host/host-main.cjs') + return member.read() + return None + + +class PinnedPatchTests(unittest.TestCase): + def setUp(self): + self.raw = bytes(range(256)) * 8 + self.target = self.raw[:300] + b'project addition' + self.raw[500:] + self.recipe = bytepatch.create(self.raw, self.target) + + def test_many_targets_share_one_source_hash_but_each_recipe_checks_its_pin(self): + with patch.object(bytepatch, 'digest', wraps=bytepatch.digest) as fingerprint: + source = bytepatch.PatchSource(self.raw) + for _ in range(3): + output = io.BytesIO() + source.write_verified(self.recipe, output) + self.assertEqual(output.getvalue(), self.target) + self.assertEqual(sum(call.args == (self.raw,) for call in fingerprint.call_args_list), 1) + for changed in ({'sourceSha256': '0' * 64}, {'sourceBytes': 2}, {'targetSha256': '0' * 64}, + {'targetBytes': 1}, {'ops': [['copy', 0, len(self.raw) + 1]]}): + with self.subTest(changed=changed), self.assertRaises(ValueError): + source.write_verified({**self.recipe, **changed}, io.BytesIO()) + + def test_cached_source_cannot_be_changed_after_verification(self): + buf = bytearray(self.raw) + source = bytepatch.PatchSource(buf) + buf[0] ^= 1 + output = io.BytesIO() + source.write_verified(self.recipe, output) + self.assertEqual(output.getvalue(), self.target) + + def test_archive_digest_does_not_load_the_entire_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / 'input.bin' + data = self.raw * 2048 + path.write_bytes(data) + with patch.object(Path, 'read_bytes', side_effect=AssertionError('unbounded file read')): + self.assertEqual(bytepatch.file_digest(path), hashlib.sha256(data).hexdigest()) + + def test_reliability_manifest_checks_generated_file_digests(self): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) / 'release-reliability' + directory.mkdir() + content = b'prepared output' + (directory / 'module.mjs').write_bytes(content) + manifest = { + 'digest': 'a' * 64, + 'files': [{'name': 'module.mjs', 'sha256': hashlib.sha256(content).hexdigest()}], + } + (directory / 'manifest.json').write_text(json.dumps(manifest)) + patch_host.verify_reliability_manifest(Path(tmp)) + (directory / 'module.mjs').write_bytes(b'changed output') + with self.assertRaisesRegex(ValueError, 'Prepared reliability manifest mismatch: module.mjs'): + patch_host.verify_reliability_manifest(Path(tmp)) + + def test_tool_stream_recipe_waits_for_both_error_branches(self): + recipe = bytepatch.load(Path(__file__).resolve().parents[1] / 'recipes' / 'host' / + 'release-reliability__engine-tool-stream-executor.mjs.gbp.gz') + additions = b''.join(base64.b64decode(operation[1]) for operation in recipe['ops'] if operation[0] == 'add') + self.assertIn(b'await Promise.allSettled([stream1.throw(e), stream22.close()]', additions) + self.assertIn(b'.catch(() => interactionHandler.invocationId)', additions) + + def test_bot_id_injection_applies_to_the_complete_pinned_harness_target(self): + source = pinned_host_archive() + if source is None: + self.skipTest('set PROKBOT_TEST_HOST_ARCHIVE to run the pinned Host recipe check') + expected = { + 'recovered-core__stable__harness-turn-run-shell.mjs.gbp.gz': ( + '23657bba5e9d8a5b9cb90553312be1793b568bbe89af3d377c31cd681195911d', 769, (418, 449)), + 'release-reliability__harness-turn-run-shell.mjs.gbp.gz': ( + 'b402f015e19eae49b730ae202bd6dae3ddd16cc26f82b308a15fef87d13a48bd', 776, (421, 453)), + } + recipes = Path(__file__).resolve().parents[1] / 'recipes' / 'host' + for name, (digest, lines, positions) in expected.items(): + with self.subTest(recipe=name): + target = bytepatch.apply(source, bytepatch.load(recipes / name)) + self.assertEqual(bytepatch.digest(target), digest) + target_lines = target.splitlines() + self.assertEqual(len(target_lines), lines) + found = tuple(index + 1 for index, line in enumerate(target_lines) + if b'agentId: host.getConversationId()' in line) + self.assertEqual(found, positions) + + +if __name__ == '__main__': + unittest.main() diff --git a/host/tests/client-ids.test.mjs b/host/tests/client-ids.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2524a39bae997c9a65bd2ed7e195bad58b86f5f6 --- /dev/null +++ b/host/tests/client-ids.test.mjs @@ -0,0 +1,14 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { clientId } from '../server/public/ids.js'; + +test('client IDs remain usable when the admin page is served over insecure HTTP', () => { + const first = clientId('provider', {}), second = clientId('provider', {}); + assert.match(first, /^provider-[a-z0-9]+$/); + assert.match(second, /^provider-[a-z0-9]+$/); + assert.notEqual(first, second); +}); + +test('client IDs use randomUUID when the browser makes it available', () => { + assert.equal(clientId('profile', { randomUUID: () => '01234567-89ab-cdef-0123-456789abcdef' }), 'profile-01234567'); +}); diff --git a/host/tests/deployment.test.mjs b/host/tests/deployment.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8d37cfa917c65da90a9f6d77fb1bef0beb45624f --- /dev/null +++ b/host/tests/deployment.test.mjs @@ -0,0 +1,86 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { join, resolve } from 'node:path'; +import { mkdtemp, mkdir, symlink, readFile, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { createServer } from 'node:http'; +import { previousImageLink, provisionResources } from '../runtime/host-resources.mjs'; +import { checkDeploymentHealth } from '../deploy/healthcheck.mjs'; +import { HostSupervisor } from '../deploy/host-supervisor.mjs'; + +for (const [script, name] of [['deployment_checks.py', 'deployment platform and mode selection'], + ['deployment_identity.py', 'same-daemon recovery identity and shared image-tag transactions'], + ['deployment_data.py', 'Host data tree initialization'], + ['deployment_volumes.py', 'isolated upgrade, archive round trips and fail-closed recovery']]) test(name, () => { + const result = spawnSync(process.platform === 'win32' ? 'python' : 'python3', + ['-B', fileURLToPath(new URL(script, import.meta.url))], { encoding: 'utf8', timeout: 90_000 }); + assert.ifError(result.error); + assert.equal(result.status, 0, result.stdout + result.stderr); +}); + +test('remote Host health follows the same execution-node setup gate as its supervisor', async t => { + const data = await mkdtemp(join(tmpdir(), 'host-health-')); + t.after(() => rm(data, { recursive: true, force: true })); + const requests = []; + const admin = createServer((req, res) => { + requests.push(req.url); + res.writeHead(req.url === '/healthz' ? 200 : 503, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ ok: req.url === '/healthz' })); + }); + await new Promise(resolve => admin.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise(resolve => { admin.close(resolve); admin.closeAllConnections(); })); + const env = { GROKBOT_PORT: String(admin.address().port), GROKBOT_DATA_DIR: data, GROKBOT_REQUIRE_EXECUTION_NODE: '1', + GROKBOT_INTERNAL_HOST_URL: `http://127.0.0.1:${admin.address().port}` }; + await writeFile(join(data, 'model.env'), 'OPENAI_BASE_URL=fixture\nOPENAI_API_KEY=fixture\nOPENAI_MODEL=fixture\n'); + const nodeFile = join(data, 'execution-node.json'); + assert.equal(await checkDeploymentHealth(env), true, 'execution node has not been configured yet'); + await writeFile(nodeFile, JSON.stringify({ version: 1, config: { enabled: false } })); + assert.equal(await checkDeploymentHealth(env), true); + assert.deepEqual(requests, ['/healthz', '/healthz']); + await writeFile(nodeFile, JSON.stringify({ version: 1, config: { enabled: true } })); + assert.equal(await checkDeploymentHealth(env), false, 'a configured deployment must not mask a missing Host'); + await writeFile(nodeFile, '{'); + assert.equal(await checkDeploymentHealth(env), false, 'unreadable configuration is not a setup state'); +}); + +test('shutdown while writing startup status must not spawn a new Host', async t => { + const data = await mkdtemp(join(tmpdir(), 'host-shutdown-')); + t.after(() => rm(data, { recursive: true, force: true })); + const supervisor = new HostSupervisor({ dataDir: data, isConfigured: async () => true }); + let writing, finish; + const began = new Promise(resolve => { writing = resolve; }); + const flushed = new Promise(resolve => { finish = resolve; }); + supervisor.status = async () => { writing(); await flushed; }; + let starts = 0; + supervisor.startHost = () => { starts++; }; + supervisor.start(); + await began; + const stopped = supervisor.stop(); + finish(); + await stopped; + assert.equal(starts, 0); +}); + +test('only resource links from a sibling image revision belong to the updater', () => { + const root = resolve('artifacts'), current = join(root, 'host-abc', 'sand-host'); + assert.ok(previousImageLink(join(root, 'host-def', 'sand-host', 'version'), current, 'version')); + for (const target of [join(current, 'version'), join(root, 'host-def', 'sand-host', 'other'), + join(root, 'user', 'sand-host', 'version'), resolve('other', 'host-def', 'sand-host', 'version')]) { + assert.equal(previousImageLink(target, current, 'version'), false); + } +}); + +test('refreshes a dangling image link but preserves user files and links', { skip: process.platform === 'win32' }, async t => { + const root = await mkdtemp(join(tmpdir(), 'host-upgrade-')); + t.after(() => rm(root, { recursive: true, force: true })); + const src = join(root, 'host-abc', 'sand-host'), state = join(root, 'state'); + await mkdir(src, { recursive: true }); await mkdir(state); + for (const name of ['version', 'data', 'link']) await writeFile(join(src, name), 'new'); + await symlink(join(root, 'host-def', 'sand-host', 'version'), join(state, 'version')); + await writeFile(join(state, 'data'), 'mine'); await symlink(join(state, 'data'), join(state, 'link')); + await provisionResources(state, src); + assert.equal(await readFile(join(state, 'version'), 'utf8'), 'new'); + for (const name of ['data', 'link']) assert.equal(await readFile(join(state, name), 'utf8'), 'mine'); +}); diff --git a/host/tests/deployment_checks.py b/host/tests/deployment_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..7c14ec2d0098c9315fc4c9a5708aeaed97f24ac5 --- /dev/null +++ b/host/tests/deployment_checks.py @@ -0,0 +1,309 @@ +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import sys +import tempfile +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, patch + +HOST = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(HOST)) +import deploy +import backup +import platforms + +spec = importlib.util.spec_from_file_location('builder', HOST / 'release/build-docker.py') +builder = importlib.util.module_from_spec(spec) +spec.loader.exec_module(builder) + + +class DeploymentTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.home = Path(temp.name) + self.args = ['--home', str(self.home)] + + def invoke(self, *args): + with contextlib.redirect_stdout(io.StringIO()) as out: + deploy.main(self.args + list(args)) + return out.getvalue() + + def test_platforms(self): + for arch in ('amd64', 'x86_64', 'arm64', 'aarch64'): + self.assertEqual(platforms.host_platform('Linux', arch), 'linux/' + ('arm64' if arch in ('arm64', 'aarch64') else 'amd64')) + for os_name, arch in [('windows', 'amd64'), ('linux', 'armv7l')]: + with self.assertRaises(ValueError): platforms.host_platform(os_name, arch) + + def test_runtime_matrix(self): + for mode in (True, False): + self.assertEqual(builder.choose_runtime('linux/amd64', mode), (platforms.BOX['localTag'], True)) + image, needs_box = builder.choose_runtime('linux/arm64', mode) + self.assertNotEqual(image, platforms.BOX['localTag']); self.assertEqual(needs_box, not mode) + + def test_arm_probe_precedes_download(self): + with patch.object(sys, 'argv', ['build']), patch.object(builder, 'docker_platform', return_value='linux/arm64'), \ + patch.object(builder, 'check_box_execution', side_effect=ValueError('no emulator')), patch.object(builder, 'prepare_box') as box: + with self.assertRaisesRegex(ValueError, 'no emulator'): builder.main() + box.assert_not_called() + + def test_arm_remote_skips_box_and_emulator(self): + with patch.object(sys, 'argv', ['build', '--host-only', '--host-archive', str(self.home / 'missing')]), \ + patch.object(builder, 'docker_platform', return_value='linux/arm64'), patch.object(builder, 'check_box_execution') as probe, \ + patch.object(builder, 'prepare_box') as box: + with self.assertRaises(FileNotFoundError): builder.main() + box.assert_not_called(); probe.assert_not_called() + + def test_init_once_and_mode(self): + with patch.object(deploy, 'check_runtime_versions', return_value={}): + self.invoke('--host-only', '--project', 'mybot', 'init', '--listen', '::1', '--public-url', 'http://[::1]:18080') + env = (self.home / '.env').read_text() + self.assertIn('GROKBOT_LISTEN_ADDRESS=[::1]', env) + with patch.object(deploy, 'check_runtime_versions', return_value={}), \ + self.assertRaisesRegex(ValueError, 'never overwrites'): + self.invoke('init') + self.assertEqual(env, (self.home / '.env').read_text()) + with patch.object(deploy, 'run') as run: self.invoke('status') + self.assertIn('mybot', run.call_args.args[0]); self.assertIn(str(deploy.RELEASE / 'compose.host.yaml'), run.call_args.args[0]) + with self.assertRaisesRegex(ValueError, 'Project name conflicts'): self.invoke('--project', 'other', 'status') + + def test_invalid_url_writes_nothing(self): + for url in ['http://bot/path', 'http://user@bot', 'https://bot:65536', 'http://bot?key=x', 'https://bot:0']: + with self.assertRaises(ValueError): self.invoke('init', '--public-url', url) + self.assertFalse((self.home / '.env').exists()) + + def test_preflight_failure_is_json(self): + with patch.object(deploy, 'docker_platform', side_effect=ValueError('unsupported')), contextlib.redirect_stdout(io.StringIO()) as out: + with self.assertRaises(SystemExit) as failure: deploy.main(self.args + ['doctor']) + self.assertEqual(failure.exception.code, 1); self.assertFalse(json.loads(out.getvalue())['ok']) + + def test_archive_flags_keep_pinned_build_path(self): + archive = self.home / 'original.tgz'; archive.touch() + args = SimpleNamespace(host_only=True, host_archive=archive, box_archive=None) + with patch.object(deploy, 'run') as called: deploy.build(args, 'candidate') + self.assertEqual(called.call_args.args[0][-3:], ['--host-only', '--host-archive', str(archive.resolve())]) + + def test_runtime_versions_require_subpath_capable_engine_and_compose(self): + def versions(server, compose='2.26.0'): + def run(cmd, **kwargs): + if cmd[1] == 'version': + return SimpleNamespace(stdout=json.dumps(server)) + self.assertEqual(cmd, ['docker', 'compose', 'version', '--short']) + return SimpleNamespace(stdout=compose) + return run + + server = {'Version': '26.0.0', 'ApiVersion': '1.45'} + with patch.object(deploy, 'run', side_effect=versions(server)): + self.assertEqual(deploy.check_runtime_versions(), { + 'dockerEngineVersion': '26.0.0', 'dockerApiVersion': '1.45', 'composeVersion': '2.26.0'}) + ubuntu = {'Version': '26.1.5+dfsg1', 'ApiVersion': '1.45'} + with patch.object(deploy, 'run', side_effect=versions(ubuntu, '2.40.3+ds1-0ubuntu1~24.04.1')): + self.assertEqual(deploy.check_runtime_versions()['composeVersion'], '2.40.3') + for old_server, old_compose, message in [ + ({'Version': '25.0.9', 'ApiVersion': '1.44'}, '2.26.0', 'Docker Engine 25.0.9 is too old'), + ({'Version': '26.0.0', 'ApiVersion': '1.44'}, '2.26.0', 'Docker API 1.44.0 is too old'), + (server, '2.25.0', 'Docker Compose 2.25.0 is too old'), + (server, '2.25.0+ds1-0ubuntu1~22.04.1', 'Docker Compose 2.25.0 is too old'), + (server, 'dev', 'usable Compose version'), + ]: + with self.subTest(message=message), patch.object(deploy, 'run', side_effect=versions(old_server, old_compose)): + with self.assertRaisesRegex(ValueError, message): + deploy.check_runtime_versions() + + def test_init_and_update_reject_old_runtime_before_writing_or_building(self): + with patch.object(deploy, 'check_runtime_versions', side_effect=ValueError('runtime too old')): + with self.assertRaisesRegex(ValueError, 'runtime too old'): + self.invoke('init') + self.assertFalse((self.home / '.env').exists()) + + (self.home / '.env').write_text('PROKBOT_MODE=local\nPROKBOT_PROJECT=demo\n', encoding='utf-8') + with patch.object(deploy, 'check_runtime_versions', side_effect=ValueError('runtime too old')), \ + patch.object(deploy, 'build') as build: + with self.assertRaisesRegex(ValueError, 'runtime too old'): + self.invoke('update') + build.assert_not_called() + + def test_host_only_skips_subpath_runtime_gate(self): + with patch.object(deploy, 'check_runtime_versions', side_effect=ValueError('runtime too old')) as gate: + self.invoke('--host-only', 'init') + with patch.object(deploy, 'operate') as operate, \ + patch.object(deploy.volume_backup, 'project_lock', return_value=contextlib.nullcontext()): + self.invoke('--host-only', 'update') + operate.assert_called_once() + gate.assert_not_called() + self.assertIn('PROKBOT_MODE=remote', (self.home / '.env').read_text()) + + +class ComposeMountTests(unittest.TestCase): + dc = ['docker', 'compose', '-p', 'demo'] + image_id = 'sha256:' + '1' * 64 + + @staticmethod + def config(existing=False, box=False): + specs = {'host': ('host:local', [('host-data', '/data')])} + if box: + specs['box'] = (deploy.BOX['localTag'], [('box-home', '/home/box'), ('box-workspace', '/workspace')]) + services, volumes = {}, {} + for service, (image, pairs) in specs.items(): + services[service] = {'image': image, 'volumes': [ + {'type': 'volume', 'source': name, 'target': dest} for name, dest in pairs]} + if service == 'box': + services[service]['volumes'].extend( + {'type': 'volume', 'source': 'host-data', 'target': target, + 'volume': {'subpath': str(backup.DATA_SOURCE_ROOT / tree)}} + for target, tree in backup.BOX_DATA_TARGETS.items()) + for name, _ in pairs: + volumes[name] = {'name': 'demo_' + name} + if existing: + volumes[name]['external'] = True + return {'services': services, 'volumes': volumes} + + @contextlib.contextmanager + def config_only(self, config, existing, pinned=None): + def read(cmd, **kwargs): + self.assertEqual(cmd, self.dc + ['config', '--format', 'json']) + self.assertTrue(kwargs['capture']) + env = kwargs['env'] + self.assertEqual(env['PROKBOT_EXISTING_VOLUMES'], 'true' if existing else 'false') + for service, image in (pinned or {}).items(): + self.assertEqual(env['GROKBOT_' + service.upper() + '_IMAGE'], image) + return SimpleNamespace(stdout=json.dumps(config)) + + with patch.object(deploy, 'run', side_effect=read) as run, \ + patch('subprocess.Popen', side_effect=AssertionError('Unexpected external process')): + try: + yield + finally: + run.assert_called_once() + + def images(self, config, existing=False): + with self.config_only(config, existing): + return deploy.instance_images(self.dc, 'demo', tuple(config['services']), existing) + + def test_supported_mounts_and_non_overlapping_tmpfs(self): + for box in (False, True): + for existing in (False, True): + with self.subTest(box=box, existing=existing): + config = self.config(existing, box) + services = config['services'] + images = {s: v['image'] for s, v in services.items()} + self.assertEqual(self.images(config, existing), images) + services['host']['volumes'].insert(0, {'type': 'tmpfs', 'target': '/database'}) + services['host']['tmpfs'] = '/run:mode=0700' + if box: + services['box']['volumes'].reverse() + services['box']['tmpfs'] = ['/home/box-old', '/run:mode=0700'] + self.assertEqual(self.images(config, existing), images) + + def test_rejects_extra_duplicate_and_shadowing_mounts(self): + cases = [('host', 'bind', '/fixture', '/logs'), ('host', 'volume', 'extra', '/logs'), + ('host', 'volume', None, '/scratch'), ('host', 'volume', 'host-data', '/copy'), + ('host', 'volume', 'host-data', '/data'), ('host', 'bind', '/fixture', '/data'), + ('host', 'volume', 'extra', '/data/uploads'), ('box', 'bind', '/fixture', '/workspace/logs'), + ('box', 'bind', '/fixture', '/home/box/sand-data/agents'), + ('box', 'volume', 'host-data', '/data/runtime/host-data/agent-transcripts'), + ('host', 'tmpfs', None, '/'), ('box', 'tmpfs', None, '/home'), + ('host', 'tmpfs', None, '//data/.'), ('host', 'tmpfs', None, '/scratch/../data/cache')] + for service, kind, source, target in cases: + with self.subTest(service=service, kind=kind, target=target): + config = self.config(box=True) + mount = {'type': kind, 'target': target} + if source is not None: + mount['source'] = source + if source == 'extra': + config['volumes'][source] = {'name': 'demo_extra'} + config['services'][service]['volumes'].append(mount) + with self.assertRaisesRegex(ValueError, service): + self.images(config) + + def test_checks_mounts_outside_service_volumes_list(self): + for key, value in [('tmpfs', '/data:mode=0700'), ('tmpfs', ['/data/cache:size=64k']), + ('tmpfs', ['/run/.:mode=0700']), ('volumes_from', ['container:peer']), + ('configs', [{'source': 'cfg', 'target': '/data/cfg'}]), + ('secrets', [{'source': 'key'}]), ('use_api_socket', True)]: + with self.subTest(key=key, value=value): + config = self.config() + config['services']['host']['volumes'].append({'type': 'tmpfs', 'target': '/run'}) + config['services']['host'][key] = value + if key in ('configs', 'secrets'): + config[key] = {value[0]['source']: {'file': '/fixture'}} + with self.assertRaisesRegex(ValueError, 'host'): + self.images(config) + + def test_required_volume_is_still_exact_and_writable(self): + for mount, volume in [(None, {}), ({'source': 'other'}, {}), ({'read_only': True}, {}), + ({'type': 'tmpfs'}, {}), ({}, {'name': 'other_host-data'}), ({}, {'external': True})]: + with self.subTest(mount=mount, volume=volume): + config = self.config() + mounts = config['services']['host']['volumes'] + if mount is None: + mounts.clear() + else: + mounts[0].update(mount) + config['volumes']['host-data'].update(volume) + with self.assertRaisesRegex(ValueError, '/data'): + self.images(config) + + def test_existing_volume_subdirectory_is_not_the_managed_data_root(self): + for service, expected in [('host', '/data'), ('box', '/home/box')]: + with self.subTest(service=service): + config = self.config(existing=True, box=True) + mount = config['services'][service]['volumes'][0] + mount['volume'] = {'nocopy': True} + self.assertIn(service, self.images(config, existing=True)) + mount['volume']['subpath'] = 'other-instance' + with self.assertRaisesRegex(ValueError, expected): + self.images(config, existing=True) + + def test_new_install_and_update_reject_before_inventory(self): + for action in ('up', 'update'): + with self.subTest(action=action): + existing = action == 'update' + config = self.config(existing) + config['services']['host']['tmpfs'] = ['/data/cache'] + args = SimpleNamespace(action=action, host_only=True, project='demo') + with self.config_only(config, existing), patch.object(deploy, 'inventory') as inventory: + with self.assertRaisesRegex(ValueError, '/data/cache'): + deploy.operate(args, None, self.dc) + inventory.assert_not_called() + + def test_last_preflight_rejects_before_compose_up(self): + images = {'host': self.image_id} + for existing in (False, True): + with self.subTest(existing=existing): + config = self.config(existing) + config['services']['host'].update(image=self.image_id, tmpfs=['/data/cache']) + with self.config_only(config, existing, images), self.assertRaisesRegex(ValueError, '/data/cache'): + deploy.up_and_wait(self.dc, 'demo', ('host',), images, existing=existing) + + def test_post_build_preflight_rejects_before_stop_or_backup(self): + config = self.config(existing=True) + config['services']['host']['tmpfs'] = ['/data/cache'] + old = {'host': {'Id': 'original', 'Image': self.image_id, 'State': {'Status': 'running'}}} + staged = contextlib.nullcontext({'host': 'sha256:' + '2' * 64}) + with self.config_only(config, True), patch.object(deploy, 'tag_state', return_value=self.image_id), \ + patch.object(deploy, 'image_id', return_value=self.image_id), patch.object(deploy, 'staged_host', return_value=staged), \ + patch.object(deploy, 'inventory', return_value=old), patch.object(deploy, 'backup') as backup: + with self.assertRaisesRegex(ValueError, '/data/cache'): + deploy.upgrade(SimpleNamespace(project='demo'), None, self.dc, ('host',), 'host:local', old, 'demo', False) + backup.assert_not_called() + + def test_recovery_preflight_rejects_before_writing_volumes(self): + config = self.config(existing=True) + config['services']['host'].update(image=self.image_id, tmpfs=['/data/cache']) + images = {'host': self.image_id} + manifest = {'project': 'original', 'serviceImages': images, 'volumes': [{'suffix': 'host-data'}]} + args = SimpleNamespace(project='demo', directory=Mock(spec=Path)) + with self.config_only(config, True, images), patch.object(deploy.volume_backup, 'read_manifest', return_value=manifest), \ + patch.object(deploy, 'image_id', return_value=self.image_id), patch.object(deploy, 'check_platform'), \ + patch.object(deploy.volume_backup, 'restore') as restore: + with self.assertRaisesRegex(ValueError, '/data/cache'): + deploy.recover(args, None, self.dc, ('host',)) + restore.assert_not_called() + + +if __name__ == '__main__': + unittest.main() diff --git a/host/tests/deployment_data.py b/host/tests/deployment_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d5cf4ae0e0f620275e8c6bd88778524595d5dc42 --- /dev/null +++ b/host/tests/deployment_data.py @@ -0,0 +1,90 @@ +import os +from pathlib import Path +import shutil +import sys +import tempfile +import unittest + +HOST = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(HOST / 'release')) +import data_init + + +class DataInitTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) / 'host-data' + self.options = {'trusted_root': self.root.parent} + if os.name == 'posix': + self.options.update(uid=os.getuid(), gid=os.getgid()) + + def initialise(self): + return data_init.initialise(self.root, **self.options) + + def test_new_volume_creates_only_the_five_approved_trees(self): + result = self.initialise() + self.assertTrue(result['rootCreated']) + self.assertEqual(set(result['created']), set(data_init.DATA_TREES)) + self.assertEqual({path.name for path in self.root.iterdir()}, set(data_init.DATA_TREES)) + self.assertNotIn('connector-secrets', {path.name for path in self.root.iterdir()}) + if os.name == 'posix': + for tree in data_init.DATA_TREES: + self.assertEqual((self.root/tree).stat().st_mode & 0o777, 0o750) + + def test_existing_data_and_nested_metadata_are_not_rewritten(self): + tree = self.root/'agents'/'agent-one'/'memory' + tree.mkdir(parents=True) + profile = tree/'profile.md' + profile.write_text('remember me', encoding='utf-8') + agents = self.root/'agents' + if os.name == 'posix': + agents.chmod(0o711) + os.chown(agents, os.getuid(), os.getgid()) + os.utime(agents, ns=(1_700_000_000_000_000_000, 1_700_000_000_000_000_000)) + top_before = agents.stat() + before = profile.stat() + result = self.initialise() + after = profile.stat() + top_after = agents.stat() + self.assertEqual(set(result['created']), set(data_init.DATA_TREES) - {'agents'}) + self.assertEqual(profile.read_text(encoding='utf-8'), 'remember me') + self.assertEqual((before.st_ino, before.st_mode, before.st_mtime_ns), + (after.st_ino, after.st_mode, after.st_mtime_ns)) + if os.name == 'posix': + self.assertEqual((top_before.st_uid, top_before.st_gid, top_before.st_mode, top_before.st_mtime_ns), + (top_after.st_uid, top_after.st_gid, top_after.st_mode, top_after.st_mtime_ns)) + + def test_existing_tree_is_idempotent(self): + first = self.initialise() + second = self.initialise() + self.assertEqual(set(first['created']), set(data_init.DATA_TREES)) + self.assertEqual(second['created'], []) + self.assertFalse(second['rootCreated']) + + def test_file_and_symlink_trees_are_rejected_without_following_them(self): + self.root.mkdir() + (self.root/'agents').write_text('not a directory', encoding='utf-8') + with self.assertRaisesRegex(ValueError, 'not a directory'): + self.initialise() + + (self.root/'agents').unlink() + outside = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, outside) + (self.root/'agents').symlink_to(outside, target_is_directory=True) + with self.assertRaisesRegex(ValueError, 'symlink'): + self.initialise() + self.assertEqual(list(outside.iterdir()), []) + + def test_symlink_parent_is_rejected(self): + base = self.root.parent + outside = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, outside) + (base/'runtime').symlink_to(outside, target_is_directory=True) + with self.assertRaisesRegex(ValueError, 'symlink'): + data_init.initialise(base/'runtime'/'host-data', trusted_root=base, **{k: v for k, v in self.options.items() if k != 'trusted_root'}) + self.assertEqual(list(outside.iterdir()), []) + + +if __name__ == '__main__': + unittest.main() diff --git a/host/tests/deployment_identity.py b/host/tests/deployment_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..7879296d2701f4f1726d01cdac0290022920dfc7 --- /dev/null +++ b/host/tests/deployment_identity.py @@ -0,0 +1,452 @@ +"""Same-daemon identity and shared-tag transactions, without a Docker socket.""" +import contextlib +import io +import json +import subprocess +import unittest +from unittest.mock import patch + +import deployment_volumes as fixtures +from deployment_volumes import backup, deploy, PROJECT, HOST_TAG, OLD, NEW + + +class IdentityTests(unittest.TestCase): + def setUp(self): + self.f = fixtures.VolumeTests() + self.f.setUp() + self.addCleanup(self.f.doCleanups) + self.engine = self.f.e + self.source = self.f.source + + def home(self, project, port): + args = ['--home', str(self.f.home.parent/('home-'+project)), '--project', project] + deploy.main([*args, '--host-only', 'init', '--port', str(port)]) + return args + + def original(self): + home = self.home(PROJECT, 18080) + self.f.snapshot(('host',)) + self.engine.docker(['stop', 'demo-host']) + return home + + def recover(self, args, source=None): + deploy.main([*args, 'recover', '--directory', str(source or self.source)]) + + def assert_no_activation(self, call): + start = len(self.engine.calls) + with self.assertRaises((ValueError, RuntimeError)): + call() + self.assertFalse(any(c[0] in ('build', 'stop', 'start', 'pause', 'run') or 'up' in c for c in self.engine.calls[start:])) + + def test_same_backup_cannot_start_twice_on_two_ports(self): + self.original() + first = self.home('first', 18081) + second = self.home('second', 18082) + self.recover(first) + self.assert_no_activation(lambda: self.recover(second)) + self.assertEqual(self.engine.containers['first-host']['State']['Status'], 'running') + self.assertNotIn('second_host-data', self.engine.labels) + + def test_nested_snapshot_keeps_root_and_prevents_original_or_sibling_restart(self): + origin = self.original() + first = self.home('first', 18081) + self.recover(first) + nested = self.f.home.parent/'nested' + backup.backup('first', nested, OLD) + self.engine.docker(['stop', 'first-host']) + self.recover(self.home('nested', 18082), nested) + self.assert_no_activation(lambda: deploy.main([*origin, 'update'])) + self.assert_no_activation(lambda: deploy.main([*first, 'update'])) + self.assert_no_activation(lambda: self.recover(self.home('sibling', 18083))) + self.assertEqual(self.engine.containers['nested-host']['State']['Status'], 'running') + + def test_concurrent_recovery_via_different_immediate_parents_has_one_winner(self): + self.original() + first = self.home('first', 18081) + self.recover(first) + nested = self.f.home.parent/'nested' + backup.backup('first', nested, OLD) + self.engine.docker(['stop', 'first-host']) + other = self.home('other', 18082) + target = self.home('target', 18083) + def competing(): + self.engine.before_up = lambda: None + self.assert_no_activation(lambda: self.recover(other, nested)) + self.engine.before_up = competing + self.recover(target) + self.assertNotIn('other_host-data', self.engine.labels) + self.assertEqual(self.engine.containers['target-host']['State']['Status'], 'running') + + def test_only_unmarked_legacy_restored_volumes_do_not_prove_a_distinct_identity(self): + origin = self.original() + target = self.home('target', 18082) + self.engine.volume('legacy_host-data', {'com.docker.compose.project':'legacy', 'com.docker.compose.volume':'host-data'}) + self.assert_no_activation(lambda: self.recover(target)) + self.assert_no_activation(lambda: deploy.main([*origin, 'update'])) + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'exited') + + def test_legacy_restore_id_without_lineage_cannot_be_promoted_by_a_new_backup(self): + self.original() + self.engine.stack(('host',), project='oldcopy') + self.engine.labels['oldcopy_host-data'][backup.RESTORE_LABEL] = 'old-operation' + self.engine.docker(['stop', 'oldcopy-host']) + unknown = self.f.home.parent/'legacy-snapshot' + backup.backup('oldcopy', unknown, OLD) + self.assert_no_activation(lambda: self.recover(self.home('target', 18082), unknown)) + self.assert_no_activation(lambda: deploy.main([*self.home('oldcopy', 18081), 'update'])) + + def test_recover_without_lineage_is_data_only_even_if_image_ids_exist(self): + self.original() + path = self.source/'manifest.json' + manifest = json.loads(path.read_bytes()) + manifest.pop('lineageRoot', None) + path.write_text(json.dumps(manifest)) + self.assert_no_activation(lambda: self.recover(self.home('target', 18082))) + backup.restore(self.source, 'offline', OLD) + self.assertFalse(self.engine.ids('offline')) + + def test_solitary_unmarked_legacy_volume_never_becomes_its_own_root(self): + self.engine.stack(('host',)) + self.engine.labels['demo_host-data'].pop('com.docker.compose.version') + self.engine.docker(['stop', 'demo-host']) + backup.backup(PROJECT, self.source, OLD) + self.assertIsNone(json.loads((self.source/'manifest.json').read_bytes()).get('lineageRoot')) + self.assert_no_activation(lambda: self.recover(self.home('target', 18082))) + self.assert_no_activation(lambda: deploy.main([*self.home(PROJECT, 18080), 'update'])) + + def test_foreign_compose_volumes_and_own_lock_suffix_do_not_block_managed_operations(self): + origin = self.original() + for name, role in [('cache_host-data', 'cache-data'), ('custom-database', 'host-data')]: + self.engine.volume(name, {backup.PROJECT_LABEL: 'other', backup.VOLUME_LABEL: role, backup.VERSION_LABEL: '2.40.3'}) + deploy.main([*origin, 'backup']) + deploy.main([*self.home('team_host-data', 18085), 'up']) + self.recover(self.home('restored', 18086)) + self.assertEqual(self.engine.containers['restored-host']['State']['Status'], 'running') + + def test_unknown_offline_restore_stays_offline_but_does_not_block_creation_of_empty_new_identity(self): + origin = self.original(); path = self.source/'manifest.json' + manifest = json.loads(path.read_bytes()); manifest.pop('lineageRoot'); path.write_text(json.dumps(manifest)) + backup.restore(self.source, 'offline', OLD) + self.assert_no_activation(lambda: deploy.main([*origin, 'update'])) + deploy.main([*self.home('fresh', 18087), 'up']) + self.assertEqual(self.engine.containers['fresh-host']['State']['Status'], 'running') + self.assertEqual(self.engine.ids('offline'), []) + + def test_unlabelled_foreign_volume_user_or_unreadable_state_cannot_bypass_lineage_gate(self): + self.original() + mounts = self.engine.containers['demo-host']['Mounts'] + cid = self.engine.container('other', 'outside', mounts, OLD) + self.engine.containers[cid]['Config']['Labels'] = {'com.docker.compose.project': 'outside'} + target = self.home('target', 18082) + self.assert_no_activation(lambda: self.recover(target)) + self.engine.fail = lambda c: c[0] == 'inspect' and c[-1] == cid + with self.assertRaises(subprocess.CalledProcessError): self.recover(target) + self.assertNotIn('target_host-data', self.engine.labels) + + def test_stopped_sibling_can_transfer_activation_and_unrelated_managed_hosts_can_coexist(self): + self.original() + self.recover(self.home('first', 18081)) + self.engine.docker(['stop', 'first-host']) + self.recover(self.home('second', 18082)) + self.assertEqual(self.engine.containers['second-host']['State']['Status'], 'running') + self.engine.docker(['stop', 'second-host']) + fresh = self.home('fresh', 18083) + deploy.main([*fresh, 'up']) + self.recover(self.home('third', 18084)) + self.assertTrue(all(self.engine.containers[n+'-host']['State']['Status'] == 'running' for n in ('fresh', 'third'))) + + def test_update_recovered_host_with_only_immutable_image_and_no_public_tag(self): + self.original() + target = self.home('restored', 18081) + del self.engine.images[HOST_TAG] + self.recover(target) + deploy.main([*target, 'update']) + self.assertEqual(self.engine.images[HOST_TAG], NEW) + self.assertEqual(self.engine.containers['restored-host']['Image'], NEW) + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'exited') + + def test_inventory_error_is_never_treated_as_a_missing_tag(self): + self.f.invoke('--host-only', 'init') + self.engine.stack(('host',)) + del self.engine.images[HOST_TAG] + self.engine.fail = lambda c: c[:2] == ['image','ls'] + with self.assertRaises(subprocess.CalledProcessError): self.f.invoke('update') + self.assertTrue(any(c[:2] == ['image','ls'] for c in self.engine.calls)) + self.assertFalse(any(c[0] in ('build','stop') for c in self.engine.calls)) + + def test_failed_inspect_of_listed_tag_is_not_absence(self): + self.f.invoke('--host-only', 'init') + self.engine.stack(('host',)) + self.engine.fail = lambda c: c[:2] == ['image','inspect'] and c[-1] == HOST_TAG + with self.assertRaises(subprocess.CalledProcessError): self.f.invoke('update') + self.assertEqual(self.engine.images[HOST_TAG], OLD) + self.assertFalse(any(c[0] in ('build','stop') for c in self.engine.calls)) + + def test_repository_without_tag_queries_only_latest_not_all_repository_tags(self): + with patch.object(deploy, 'run', wraps=deploy.run) as calls: + self.assertIsNone(deploy.tag_state('grokbot-host')) + self.assertEqual(calls.call_args.args[0][-1], 'grokbot-host:latest') + + def test_new_install_failure_restores_existing_public_tag_of_other_projects(self): + fresh = self.home('fresh', 18083) + self.engine.unhealthy = True + with self.assertRaises(RuntimeError): deploy.main([*fresh, 'up']) + self.assertEqual(self.engine.images[HOST_TAG], OLD) + self.assertEqual(self.engine.containers['fresh-host']['State']['Status'], 'exited') + self.assertTrue((self.f.restored('fresh','host-data')/'partial-migration').exists()) + + def test_external_tag_change_is_never_clobbered_by_rollback(self): + self.f.invoke('--host-only', 'init') + self.engine.stack(('host',)) + other = 'sha256:' + '9'*64 + command = self.engine.docker + def concurrent(cmd, **kw): + result = command(cmd, **kw) + if list(cmd) == ['image', 'tag', NEW, HOST_TAG]: + self.engine.images[HOST_TAG] = other + self.engine.error(cmd) + return result + with patch.object(self.engine, 'docker', concurrent), self.assertRaisesRegex(RuntimeError, 'rollback NOT confirmed'): + self.f.invoke('update') + self.assertEqual(self.engine.images[HOST_TAG], other) + self.assertEqual(self.engine.containers['demo-host']['Image'], OLD) + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'running') + + def test_lost_rollback_ack_is_verified_by_observation_without_removing_old_image(self): + self.f.invoke('--host-only', 'init') + self.engine.stack(('host',)) + del self.engine.images[HOST_TAG] + command = self.engine.docker + def uncertain(cmd, **kw): + result = command(cmd, **kw) + if list(cmd) in (['image', 'tag', NEW, HOST_TAG], ['image','rm','--no-prune',HOST_TAG]): self.engine.error(cmd) + return result + with patch.object(self.engine, 'docker', uncertain), self.assertRaises(subprocess.CalledProcessError): self.f.invoke('update') + self.assertNotIn(HOST_TAG, self.engine.images) + self.assertIn(OLD, self.engine.image_ids) + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'running') + + def test_lost_publication_ack_with_originally_absent_tag_removes_only_new_alias(self): + self.f.invoke('--host-only', 'init') + self.engine.stack(('host',)) + del self.engine.images[HOST_TAG] + command = self.engine.docker + def uncertain(cmd, **kw): + result = command(cmd, **kw) + if list(cmd) == ['image', 'tag', NEW, HOST_TAG]: self.engine.error(cmd) + return result + with patch.object(self.engine, 'docker', uncertain), self.assertRaises(subprocess.CalledProcessError): self.f.invoke('update') + self.assertIn(['image', 'tag', NEW, HOST_TAG], self.engine.calls) + self.assertNotIn(HOST_TAG, self.engine.images) + self.assertEqual(self.engine.containers['demo-host']['Image'], OLD) + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'running') + + def test_failed_candidate_restores_prior_tag_state_but_never_starts_old_image_on_migrated_data(self): + self.f.invoke('--host-only', 'init') + self.engine.stack(('host',)) + del self.engine.images[HOST_TAG] + self.engine.unhealthy = True + with self.assertRaisesRegex(RuntimeError, 'Project services are stopped'): self.f.invoke('update') + self.assertNotIn(HOST_TAG, self.engine.images) + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'exited') + self.assertTrue((self.f.restored(PROJECT,'host-data')/'partial-migration').exists()) + self.assertTrue(list((self.f.home/'backups').glob('*/manifest.json'))) + self.assertFalse(any(c[0] == 'start' for c in self.engine.calls)) + + def test_competing_project_cannot_publish_same_tag_inside_first_transaction(self): + first = self.home('first', 18081) + second = self.home('second', 18082) + deploy.main([*first, 'up']) + deploy.main([*second, 'up']) + def competing(): + self.engine.before_up = lambda: None + self.assert_no_activation(lambda: deploy.main([*second, 'update'])) + self.engine.before_up = competing + deploy.main([*first, 'update']) + self.assertEqual(self.engine.containers['second-host']['State']['Status'], 'running') + + def unknown_offline_fixture(self): + self.original() + path = self.source/'manifest.json' + known = json.loads(path.read_bytes()) + legacy = self.f.home.parent/'legacy-offline' + # Keep the known snapshot available for an independent recovery attempt. + legacy.mkdir() + for record in known['volumes']: + (legacy/record['file']).write_bytes((self.source/record['file']).read_bytes()) + (legacy/'manifest.json').write_text(json.dumps({k: v for k, v in known.items() if k != 'lineageRoot'})) + backup.restore(legacy, 'offline', OLD) + self.assertFalse(self.engine.ids('offline')) + return self.f.restored('offline', 'host-data')/'payload' + + def test_gate_unlabelled_cache_appearing_after_stop_allows_update_and_recovery(self): + self.f.invoke('--host-only', 'init') + self.engine.stack(('host',)) + command = self.engine.docker + def cache_arrives(cmd, **kw): + result = command(cmd, **kw) + if list(cmd) == ['stop', 'demo-host']: + path = self.engine.volume('cache_host-data', {}) + (path/'sentinel').write_bytes(b'external fixture') + self.engine.container('cache', 'other', [{'Type': 'volume', 'Name': 'cache_host-data', + 'Destination': '/cache', 'RW': True}], OLD) + return result + with patch.object(self.engine, 'docker', cache_arrives): + self.f.invoke('update') + self.assertEqual(self.engine.containers['demo-host']['Image'], NEW) + self.engine.docker(['stop', 'demo-host']) + manifests = list((self.f.home/'backups').glob('*/manifest.json')) + self.assertEqual(len(manifests), 1) + self.recover(self.home('recovered', 18081), manifests[0].parent) + self.assertEqual(self.engine.containers['recovered-host']['Image'], OLD) + self.assertEqual((self.f.restored('recovered','host-data')/'payload').read_bytes(), b'host-data: original') + self.assertEqual(self.engine.labels['cache_host-data'], {}) + self.assertEqual((self.engine.root/'cache_host-data'/'sentinel').read_bytes(), b'external fixture') + self.assertEqual(self.engine.containers['other-cache']['State']['Status'], 'running') + self.assertFalse(any(c[0] == 'run' and any('src=cache_host-data,' in v for v in c) for c in self.engine.calls)) + + def test_gate_unlabelled_cache_during_failed_backup_does_not_strand_original(self): + self.f.invoke('--host-only', 'init') + self.engine.stack(('host',)) + command = self.engine.docker + def fail_archive(cmd, **kw): + if cmd[0] == 'run' and '-czf' in cmd: + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'exited') + self.engine.volume('cache_host-data', {}) + self.engine.error(cmd) + return command(cmd, **kw) + with patch.object(self.engine, 'docker', fail_archive), self.assertRaises(subprocess.CalledProcessError): + self.f.invoke('update') + self.assertEqual([c for c in self.engine.calls if c[0] == 'start'], [['start','demo-host']]) + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'running') + self.assertEqual(self.engine.containers['demo-host']['Image'], OLD) + self.assertEqual(self.engine.images[HOST_TAG], OLD) + self.assertFalse(any('up' in c for c in self.engine.calls)) + self.assertIn('cache_host-data', self.engine.labels) + + def test_gate_first_update_of_fresh_running_host_never_activates_offline_copy(self): + offline = self.unknown_offline_fixture() + prior_bytes = offline.read_bytes() + fresh = self.home('fresh', 18082) + deploy.main([*fresh, 'up']) + active = self.f.restored('fresh', 'host-data')/'payload' + active.write_bytes(b'only the fresh instance') + start = len(self.engine.calls) + deploy.main([*fresh, 'update']) + ops = self.engine.calls[start:] + self.assertEqual([c for c in ops if c[0] == 'stop'], [['stop','fresh-host']]) + self.assertEqual([c[c.index('-p')+1] for c in ops if c[0] == 'compose' and 'up' in c], ['fresh']) + archives = [c[c.index('--mount')+1] for c in ops if c[0] == 'run' and '-czf' in c] + self.assertEqual(len(archives), 1) + self.assertIn('src=fresh_host-data,', archives[0]) + self.assertFalse(any(c[0] == 'run' and '-xzf' in c for c in ops)) + self.assertEqual(self.engine.containers['fresh-host']['State']['Status'], 'running') + self.assertEqual(self.engine.containers['demo-host']['State']['Status'], 'exited') + self.assertEqual(self.engine.ids('offline'), []) + self.assertEqual(offline.read_bytes(), prior_bytes) + self.assertEqual(active.read_bytes(), b'only the fresh instance') + + def test_gate_failed_first_update_resumes_only_previously_running_fresh_host(self): + offline = self.unknown_offline_fixture() + fresh = self.home('fresh', 18082) + deploy.main([*fresh, 'up']) + original_image = self.engine.containers['fresh-host']['Image'] + start = len(self.engine.calls) + self.engine.fail = lambda c: c[0] == 'run' and '-czf' in c + with self.assertRaises(subprocess.CalledProcessError): deploy.main([*fresh, 'update']) + self.assertEqual([c for c in self.engine.calls[start:] if c[0] in ('stop','start')], + [['stop','fresh-host'], ['start','fresh-host']]) + self.assertEqual(self.engine.containers['fresh-host']['Image'], original_image) + self.assertEqual(self.engine.containers['fresh-host']['State']['Status'], 'running') + self.assertEqual(self.engine.ids('offline'), []) + self.assertEqual(offline.read_bytes(), b'host-data: original') + + def test_failed_takeover_with_unknown_offline_copy_explains_offline_restore_before_stop(self): + offline = self.unknown_offline_fixture() + fresh = self.home('fresh', 18082) + deploy.main([*fresh, 'up']) + data = self.f.restored('fresh', 'host-data')/'payload' + previous = self.engine.containers['fresh-host']['Image'] + data.write_bytes(b'fresh before takeover') + self.engine.unhealthy = True + phases, command = [], self.engine.docker + def record(cmd, **kw): + if cmd[0] == 'stop': phases.append('stop') + return command(cmd, **kw) + def report(text, **kw): + if 'automatic recovery is blocked' in str(text): phases.append('warning') + with patch.object(self.engine, 'docker', record), patch('builtins.print', side_effect=report): + with self.assertRaises(RuntimeError) as failure: deploy.main([*fresh, 'update']) + self.assertTrue((data.parent/'partial-migration').is_file()) + self.assertEqual(self.engine.containers['fresh-host']['State']['Status'], 'exited') + saved = list((self.f.home.parent/'home-fresh'/'backups').glob('*/manifest.json')) + self.assertEqual(len(saved), 1) + source = saved[0].parent + self.assert_no_activation(lambda: self.recover(self.home('unused', 18083), source)) + backup.restore(source, 'checked', previous) + self.assertFalse(self.engine.ids('checked')); self.assertFalse(self.engine.ids('offline')) + self.assertEqual(offline.read_bytes(), b'host-data: original') + self.assertEqual((self.f.restored('checked', 'host-data')/'payload').read_bytes(), b'fresh before takeover') + self.assertFalse((self.f.restored('checked', 'host-data')/'partial-migration').exists()) + self.assertIn('automatic recovery is blocked', str(failure.exception)) + self.assertIn('data-only restore', str(failure.exception)) + self.assertIn(str(source), str(failure.exception)) + self.assertNotIn('Run recover --directory', str(failure.exception)) + self.assertEqual(phases[:2], ['warning', 'stop']) + + def test_gate_unknown_copy_with_actual_host_mount_blocks_fresh_up_and_running_update(self): + offline = self.unknown_offline_fixture() + fresh = self.home('fresh', 18082) + deploy.main([*fresh, 'up']) + blank = self.home('blank', 18083) + cid = self.engine.container('host', 'third-party', [{'Type':'volume', 'Name':'offline_host-data', + 'Destination':'/data', 'RW':True}], OLD) + self.assertFalse(self.engine.ids('offline')) # Project ownership alone misses this consumer. + for status in ('running','paused'): + if status == 'paused': self.engine.docker(['pause', cid]) + for args, action in ((blank,'up'), (fresh,'update')): + with self.subTest(status=status, action=action): + self.assert_no_activation(lambda: deploy.main([*args, action])) + self.assertEqual(self.engine.containers[cid]['State']['Status'], status) + self.assertEqual(self.engine.containers['fresh-host']['State']['Status'], 'running') + self.assertNotIn('blank_host-data', self.engine.labels) + self.assertEqual(offline.read_bytes(), b'host-data: original') + + def test_gate_unknown_copy_becoming_active_during_backup_blocks_resume(self): + offline = self.unknown_offline_fixture() + fresh = self.home('fresh', 18082) + deploy.main([*fresh, 'up']) + start = len(self.engine.calls) + command = self.engine.docker + def peer_appears(cmd, **kw): + if cmd[0] == 'run' and '-czf' in cmd: + self.engine.container('host', 'other', [{'Type':'volume', 'Name':'offline_host-data', + 'Destination':'/data', 'RW':True}], OLD) + self.engine.error(cmd) + return command(cmd, **kw) + with patch.object(self.engine, 'docker', peer_appears), self.assertRaises((ValueError, RuntimeError)): + deploy.main([*fresh, 'update']) + ops = self.engine.calls[start:] + self.assertIn(['stop','fresh-host'], ops) # A blanket preflight refusal is not a pass. + self.assertFalse(any(c[0] == 'start' or 'up' in c for c in ops)) + self.assertEqual(self.engine.containers['fresh-host']['State']['Status'], 'exited') + self.assertEqual(self.engine.containers['other-host']['State']['Status'], 'running') + self.assertEqual(offline.read_bytes(), b'host-data: original') + + def test_gate_unlabelled_cache_and_offline_restore_still_block_exact_target_collision(self): + offline = self.unknown_offline_fixture() + cache = self.engine.volume('cache_host-data', {})/'sentinel' + cache.write_bytes(b'external fixture') + for project, port in [('cache',18082), ('offline',18083)]: + target = self.home(project, port) + for action in ('up','recover'): + with self.subTest(project=project, action=action): + self.assert_no_activation(lambda: deploy.main([*target, 'up']) if action == 'up' else self.recover(target)) + self.assertEqual(self.engine.ids(project), []) + self.assertEqual(cache.read_bytes(), b'external fixture') + self.assertEqual(offline.read_bytes(), b'host-data: original') + + +if __name__ == '__main__': + with contextlib.redirect_stdout(io.StringIO()): + unittest.main() diff --git a/host/tests/deployment_volumes.py b/host/tests/deployment_volumes.py new file mode 100644 index 0000000000000000000000000000000000000000..8289a0666b6f1db0f4b18048d3c4a859adfdad13 --- /dev/null +++ b/host/tests/deployment_volumes.py @@ -0,0 +1,764 @@ +"""An isolated Docker command boundary; archive bytes come from the system tar.""" +import contextlib +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +HOST = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(HOST)) +import deploy +import backup +import data_init + +PROJECT = 'demo' +HOST_TAG = 'grokbot-host:local' +BOX_TAG = deploy.BOX['localTag'] +OLD = 'sha256:' + '1' * 64 +NEW = 'sha256:' + '2' * 64 +BOX = deploy.BOX['configDigest'] +MOUNTS = {'host': {'host-data': '/data'}, 'box': {'box-home': '/home/box', 'box-workspace': '/workspace'}, + 'gateway': {'gateway-data': '/data'}} +DATA_TARGETS = backup.BOX_DATA_TARGETS + + +class Engine: + def __init__(self, root): + self.root = root + self.root.mkdir() + self.labels, self.containers = {}, {} + self.images = {HOST_TAG: OLD, BOX_TAG: BOX} + self.image_ids = {OLD, BOX} + self.calls = [] + self.fail = lambda cmd: False + self.before_create = lambda name: None + self.after_build = lambda: None + self.before_up = lambda: None + self.unhealthy = False + self.tar = shutil.which('tar') + if not self.tar: + raise unittest.SkipTest('system tar is required for archive integration') + + def volume(self, name, labels=None): + if name not in self.labels: + self.labels[name] = labels or {} + (self.root / name).mkdir() + return self.root / name + + def stack(self, services=('host', 'box'), project=PROJECT): + for service in services: + mounts = [] + for suffix, target in MOUNTS[service].items(): + name = project + '_' + suffix + directory = self.volume(name, {'com.docker.compose.project': project, 'com.docker.compose.volume': suffix, + 'com.docker.compose.version': '2.40.3'}) + (directory / 'payload').write_bytes((suffix + ': original').encode()) + mounts.append({'Type': 'volume', 'Name': name, 'Destination': target, 'RW': True}) + self.container(service, project, mounts, self.images[HOST_TAG if service == 'host' else BOX_TAG]) + + def container(self, service, project, mounts, image): + cid = project + '-' + service + self.containers[cid] = {'Id': cid, 'Image': image, 'State': {'Status': 'running', 'Paused': False}, + 'Mounts': mounts, 'Config': {'Labels': {'com.docker.compose.project': project, + 'com.docker.compose.service': service}}} + return cid + + def ids(self, project): + return [cid for cid, c in self.containers.items() if c['Config']['Labels']['com.docker.compose.project'] == project] + + @staticmethod + def error(cmd): + raise subprocess.CalledProcessError(1, cmd) + + def docker(self, cmd, **kw): + cmd = list(cmd) + self.calls.append(cmd) + if self.fail(cmd): + self.error(cmd) + filters = [cmd[i+1] for i, v in enumerate(cmd) if v == '--filter'] + project = next((f.split('=', 2)[2] for f in filters if f.startswith('label=com.docker.compose.project=')), None) + if cmd[:2] == ['volume', 'ls']: + wanted = [f[6:].split('=', 1) for f in filters if f.startswith('label=')] + return '\n'.join(n for n, labels in self.labels.items() if all(k in labels and (not v or labels[k] == v[0]) for k, *v in wanted)) + if cmd[:2] == ['volume', 'inspect']: + name = next((v for v in cmd[2:] if v in self.labels), None) + if not name: + self.error(cmd) + return json.dumps(self.labels[name]) if '--format' in cmd else json.dumps([{'Name': name, 'Labels': self.labels[name]}]) + if cmd[:2] == ['volume', 'create']: + name = cmd[-1] + self.before_create(name) + labels = dict(cmd[i+1].split('=', 1) for i, v in enumerate(cmd) if v == '--label') + self.volume(name, labels) # Docker returns success without relabeling an existing named volume. + return name + if cmd[:2] == ['volume', 'rm']: + name = cmd[-1] + if any(m.get('Name') == name for c in self.containers.values() for m in c['Mounts']): + self.error(cmd) + self.labels.pop(name) + shutil.rmtree(self.root / name) + return name + if cmd[0] == 'ps': + ids = self.ids(project) if project else list(self.containers) + for f in filters: + if f.startswith('status='): + ids = [i for i in ids if self.containers[i]['State']['Status'] == f[7:]] + if f.startswith('volume='): + ids = [i for i in ids if any(m.get('Name') == f[7:] for m in self.containers[i]['Mounts'])] + if not ('-a' in cmd or '--all' in cmd): + ids = [i for i in ids if self.containers[i]['State']['Status'] in ('running', 'paused', 'restarting')] + return '\n'.join(ids) + if cmd[0] == 'inspect': + items = [self.containers[i] for i in cmd[1:] if i in self.containers] + if not items: + self.error(cmd) + fmt = cmd[cmd.index('--format')+1] + if fmt == '{{.State.Status}}': + return '\n'.join(c['State']['Status'] for c in items) + assert 'index .Config.Labels' in fmt and '{{json .Mounts}}' in fmt + # `.Id` makes docker inspect read the raw JSON, where a dotted key the daemon omitted + # is an error. Containers here have no HostConfig.Mounts unless a test adds them, as + # when Compose 2.40 creates named volumes as Binds. + for c in items: + host_mounts = c.get('HostConfig', {}).get('Mounts') + if ('.HostConfig.Mounts' in fmt and host_mounts is None or + '.VolumeOptions' in fmt and any('VolumeOptions' not in m for m in host_mounts or [])): + self.error(cmd) + return '\n'.join(json.dumps({'Id': c['Id'], 'State': c['State'], 'Image': c['Image'], + 'Labels': c['Config']['Labels'], 'Mounts': c['Mounts'], + 'SubpathMounts': [{'Target': m['Target'], 'Source': m.get('Source'), + 'Subpath': m['VolumeOptions']['Subpath']} + for m in c.get('HostConfig', {}).get('Mounts') or [] + if (m.get('VolumeOptions') or {}).get('Subpath')] + if 'index .HostConfig "Mounts"' in fmt else []}) for c in items) + if cmd[0] in ('pause', 'unpause', 'stop', 'start'): + c = self.containers[cmd[-1]] + status = {'pause': 'paused', 'unpause': 'running', 'stop': 'exited', 'start': 'running'}[cmd[0]] + c['State'].update(Status=status, Paused=status == 'paused') + return cmd[-1] + if cmd[0] == 'run': + entrypoint = cmd[cmd.index('--entrypoint')+1] if '--entrypoint' in cmd else None + if '--mount' in cmd: + mount = dict(item.split('=', 1) for item in cmd[cmd.index('--mount')+1].split(',') if '=' in item) + name = mount.get('src') or mount['source'] + else: + name = cmd[cmd.index('-v')+1].split(':')[0] + directory = self.volume(name) + self.assert_helper_is_local(cmd) + if entrypoint == 'python3': + assert any(str(arg).endswith('/release/data_init.py') for arg in cmd) + data_init.initialise(directory/'runtime/host-data', trusted_root=directory, + uid=os.getuid() if os.name == 'posix' else data_init.UID, + gid=os.getgid() if os.name == 'posix' else data_init.GID) + return '' + if entrypoint != 'tar': + raise AssertionError(cmd) + flags = cmd.index('-czf' if '-czf' in cmd else '-xzf') + tar_args = cmd[flags:] + tar_args[tar_args.index('-C')+1] = str(directory) + subprocess.run([self.tar, *tar_args], check=True, stdin=kw.get('stdin'), stdout=kw.get('stdout')) + return '' + if cmd[:2] == ['image', 'ls']: + return self.images.get(cmd[-1], '') + if cmd[:2] == ['image', 'inspect']: + ref = next((v for v in cmd[2:] if v in self.images or v in self.images.values() or v in self.image_ids), None) + if not ref: + self.error(cmd) + return 'linux/amd64' if '{{.Os}}/{{.Architecture}}' in cmd else self.images.get(ref, ref) + if cmd[:2] == ['image', 'tag'] or cmd[0] == 'tag': + self.images[cmd[-1]] = self.images.get(cmd[-2], cmd[-2]) + return '' + if cmd[:2] == ['image', 'rm']: + del self.images[cmd[-1]] + return '' + if cmd[:2] == ['version', '--format']: + return json.dumps({'Version': '29.1.2', 'ApiVersion': '1.52'}) + if cmd[0] == 'compose': + if 'version' in cmd: + return '2.40.3' + project = cmd[cmd.index('-p')+1] + modes = ('host',) if any(str(p).endswith('compose.host.yaml') for p in cmd) else ('host', 'box') + env = kw.get('env') or {} + external = env.get('PROKBOT_EXISTING_VOLUMES') == 'true' + refs = {'host': env.get('GROKBOT_HOST_IMAGE', HOST_TAG), 'box': env.get('GROKBOT_BOX_IMAGE', BOX_TAG)} + if 'config' in cmd: + services = {} + for s in modes: + volumes = [{'type': 'volume', 'source': n, 'target': t} for n, t in MOUNTS[s].items()] + if s == 'box': + volumes.extend({'type': 'volume', 'source': 'host-data', 'target': target, + 'volume': {'subpath': str(backup.DATA_SOURCE_ROOT/tree)}} + for target, tree in DATA_TARGETS.items()) + services[s] = {'image': refs[s], 'volumes': volumes} + return json.dumps({'services': services, + 'volumes': {n: {'name': project+'_'+n, 'external': external} for s in modes for n in MOUNTS[s]}}) + if 'ps' in cmd: + return '\n'.join(i for i in self.ids(project) if cmd[-1] not in MOUNTS or i == project+'-'+cmd[-1]) + if 'stop' in cmd: + for i in self.ids(project): + self.containers[i]['State'].update(Status='exited', Paused=False) + return '' + if 'up' in cmd: + self.before_up() + if external and any(project+'_'+suffix not in self.labels for s in modes for suffix in MOUNTS[s]): + self.error(cmd) + for s in modes: + mounts = [] + configured = [] + for suffix, target in MOUNTS[s].items(): + name = project + '_' + suffix + self.volume(name, {'com.docker.compose.project': project, 'com.docker.compose.volume': suffix, + 'com.docker.compose.version': '2.40.3'}) + mounts.append({'Type': 'volume', 'Name': name, 'Destination': target, 'RW': True}) + if s == 'box': + for target, tree in DATA_TARGETS.items(): + name = project+'_host-data' + subpath = str(backup.DATA_SOURCE_ROOT/tree) + mounts.append({'Type': 'volume', 'Name': name, 'Destination': target, 'RW': True}) + configured.append({'Type': 'volume', 'Source': name, 'Target': target, + 'VolumeOptions': {'Subpath': subpath}}) + cid = self.container(s, project, mounts, self.images.get(refs[s], refs[s])) + self.containers[cid]['HostConfig'] = {'Mounts': configured} + if self.unhealthy: + (self.root / (project + '_host-data') / 'partial-migration').touch() + self.error(cmd) + return '' + raise AssertionError(f'unimplemented simulated command: {cmd}') + + @staticmethod + def assert_helper_is_local(cmd): + assert '--pull=never' in cmd and cmd[cmd.index('--network')+1] == 'none' + assert 'volume-nocopy' in cmd[cmd.index('--mount')+1] and '--read-only' in cmd + + def deploy_run(self, cmd, **kw): + if cmd[0] != 'docker': + raise AssertionError(cmd) + return SimpleNamespace(stdout=self.docker(cmd[1:], **kw)) + + def build(self, args, image): + self.calls.append(['build', image]) + self.images[image] = NEW + self.image_ids.add(NEW) + self.after_build() + + +class VolumeTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.home = Path(tmp.name) / 'instance' + self.e = Engine(Path(tmp.name) / 'volumes') + self.source = Path(tmp.name) / 'snapshot' + for obj, name, fn in [(deploy, 'run', self.e.deploy_run), (deploy, 'build', self.e.build), + (deploy, 'docker_platform', lambda: 'linux/amd64'), + (backup, 'run', lambda *cmd, **kw: self.e.docker(cmd, **kw)), + (backup, 'output', lambda *cmd: self.e.docker(cmd))]: + mock = patch.object(obj, name, fn) + mock.start() + self.addCleanup(mock.stop) + + def invoke(self, *args): + return deploy.main(['--home', str(self.home), '--project', PROJECT, *args]) + + def snapshot(self, services=('host', 'box')): + self.e.stack(services) + backup.backup(PROJECT, self.source, HOST_TAG) + + def restored(self, project, suffix): + return self.e.root / (project + '_' + suffix) + + def add_box_data_mounts(self, *, bind=False): + container = self.e.containers[PROJECT+'-box'] + configured = [] + for target, tree in DATA_TARGETS.items(): + if bind: + container['Mounts'].append({'Type': 'bind', + 'Source': f'/srv/prokbot/runtime/host-data/{tree}', 'Destination': target, 'RW': True}) + else: + container['Mounts'].append({'Type': 'volume', 'Name': PROJECT+'_host-data', + 'Destination': target, 'RW': True}) + configured.append({'Type': 'volume', 'Source': PROJECT+'_host-data', 'Target': target, + 'VolumeOptions': {'Subpath': str(backup.DATA_SOURCE_ROOT/tree)}}) + if configured: + container['HostConfig'] = {'Mounts': configured} + return container + + def test_round_trip_preserves_three_volumes_without_starting_a_service(self): + self.snapshot() + backup.restore(self.source, 'recovered', HOST_TAG) + for suffix in ('host-data', 'box-home', 'box-workspace'): + self.assertEqual((self.restored('recovered', suffix) / 'payload').read_bytes(), (suffix + ': original').encode()) + self.assertFalse(self.e.ids('recovered')) + + def test_split_execution_backup_restores_gateway_and_desktop_without_a_host_volume(self): + self.snapshot(('gateway', 'box')) + backup.restore(self.source, 'recovered', HOST_TAG) + for suffix in ('gateway-data', 'box-home', 'box-workspace'): + self.assertEqual((self.restored('recovered', suffix)/'payload').read_bytes(), (suffix+': original').encode()) + self.assertFalse(self.restored('recovered', 'host-data').exists()) + + @unittest.skipIf(os.name == 'nt', 'POSIX volume metadata') + def test_round_trip_preserves_database_rows_binary_mode_links_and_empty_directory(self): + import sqlite3 + self.e.stack() + data = self.restored(PROJECT, 'host-data') + db = sqlite3.connect(data / 'state.db') + self.addCleanup(db.close) + db.execute('pragma journal_mode=wal') + db.execute('pragma wal_autocheckpoint=0') + db.execute('create table messages (body text)') + db.execute('insert into messages values (?)', ('fixture conversation',)) + db.commit() + self.assertGreater((data/'state.db-wal').stat().st_size, 0) + workspace = self.restored(PROJECT, 'box-workspace') + payload = workspace/'private-data' + payload.write_bytes(bytes(range(256))*9) + payload.chmod(0o600) + os.link(payload, workspace/'hardlink') + (workspace/'link').symlink_to('private-data') + (workspace/'empty').mkdir(mode=0o750) + backup.backup(PROJECT, self.source, HOST_TAG) + backup.restore(self.source, 'recovered', HOST_TAG) + with contextlib.closing(sqlite3.connect(self.restored('recovered', 'host-data')/'state.db')) as db: + self.assertEqual(db.execute('select * from messages').fetchall(), [('fixture conversation',)]) + self.assertEqual(db.execute('pragma integrity_check').fetchone(), ('ok',)) + copy = self.restored('recovered', 'box-workspace') + self.assertEqual((copy/'link').readlink(), Path('private-data')) + self.assertEqual((copy/'private-data').read_bytes(), payload.read_bytes()) + self.assertEqual((copy/'private-data').stat().st_mode & 0o777, 0o600) + self.assertTrue((copy/'hardlink').samefile(copy/'private-data')) + self.assertEqual(list((copy/'empty').iterdir()), []) + + def test_concurrent_target_creation_never_overwrites_foreign_bytes(self): + self.snapshot(('host',)) + name = 'recovered_host-data' + self.e.before_create = lambda n: (self.e.volume(n) / 'payload').write_bytes(b'keep me') if n == name else None + with self.assertRaises((ValueError, RuntimeError)): + backup.restore(self.source, 'recovered', HOST_TAG) + self.assertEqual((self.e.root / name / 'payload').read_bytes(), b'keep me') + + def test_restore_inspection_error_is_not_absence(self): + self.snapshot(('host',)) + name = 'recovered_host-data' + (self.e.volume(name) / 'payload').write_bytes(b'keep me') + self.e.fail = lambda cmd: cmd[:2] in (['volume', 'inspect'], ['volume', 'ls']) + with self.assertRaises((ValueError, subprocess.CalledProcessError)): + backup.restore(self.source, 'recovered', HOST_TAG) + self.assertEqual((self.e.root / name / 'payload').read_bytes(), b'keep me') + + def test_restore_failure_leaves_retryable_target(self): + self.snapshot() + self.e.fail = lambda cmd: cmd[0] == 'run' and any('recovered_box-home' in v for v in cmd) + with self.assertRaises((ValueError, RuntimeError, subprocess.CalledProcessError)): + backup.restore(self.source, 'recovered', HOST_TAG) + self.assertFalse(any(n.startswith('recovered_') for n in self.e.labels)) + self.e.fail = lambda cmd: False + backup.restore(self.source, 'recovered', HOST_TAG) + + def test_corrupt_or_incomplete_manifests_never_create_volumes(self): + self.snapshot() + manifest = self.source / 'manifest.json' + original = json.loads(manifest.read_text()) + records = original['volumes'] + for invalid in ([], records[1:], records + [records[0]], [*records[:-1], {**records[-1], 'file': records[0]['file']}], + [*records[:-1], {**records[-1], 'sha256': '0'*64}]): + with self.subTest(count=len(invalid)): + manifest.write_text(json.dumps({**original, 'volumes': invalid})) + with self.assertRaises(ValueError): backup.restore(self.source, 'recovered', HOST_TAG) + self.assertFalse(any(c[:2] == ['volume', 'create'] for c in self.e.calls)) + + def test_restore_refuses_a_project_even_without_matching_target_volumes(self): + self.snapshot(('host',)) + self.e.container('other', 'recovered', [], OLD) + with self.assertRaisesRegex(ValueError, 'already exists'): + backup.restore(self.source, 'recovered', HOST_TAG) + self.assertNotIn('recovered_host-data', self.e.labels) + + def test_restore_cleanup_failure_is_reported_without_claiming_success(self): + self.snapshot() + self.e.fail = lambda c: (c[0] == 'run' and any('recovered_box-home' in v for v in c)) or c[:2] == ['volume', 'rm'] + with self.assertRaisesRegex(RuntimeError, 'partial restore'): + backup.restore(self.source, 'recovered', HOST_TAG) + self.assertFalse(self.e.ids('recovered')) + with self.assertRaisesRegex(ValueError, 'already exists'): backup.restore(self.source, 'recovered', HOST_TAG) + + def test_interrupted_restore_is_not_an_upgradable_instance(self): + self.snapshot() + def interrupt(cmd): + if cmd[0] == 'run' and '-xzf' in cmd: + raise SystemExit('simulated termination without cleanup') + self.e.fail = interrupt + with self.assertRaises(SystemExit): backup.restore(self.source, 'recovered', HOST_TAG) + self.e.fail = lambda c: False + args = ['--home', str(self.home), '--project', 'recovered'] + deploy.main([*args, 'init']) + with self.assertRaisesRegex(ValueError, 'volume|Volume|restore'): deploy.main([*args, 'update']) + self.assertFalse(any('up' in c for c in self.e.calls)) + + def test_lost_volume_create_acknowledgement_cleans_only_our_volume(self): + self.snapshot(('host',)) + create = self.e.docker + def uncertain(cmd, **kw): + result = create(cmd, **kw) + if list(cmd[:2]) == ['volume', 'create'] and cmd[-1] == 'recovered_host-data': + self.e.error(cmd) + return result + with patch.object(self.e, 'docker', uncertain), self.assertRaises(subprocess.CalledProcessError): + backup.restore(self.source, 'recovered', HOST_TAG) + self.assertFalse(any(n.startswith('recovered_') for n in self.e.labels)) + + def test_backup_rejects_active_foreign_writer_without_pausing_it(self): + self.e.stack(('host',)) + self.e.container('sidecar', 'another', self.e.containers['demo-host']['Mounts'], OLD) + with self.assertRaisesRegex(ValueError, 'container|writer|project'): + backup.backup(PROJECT, self.source, HOST_TAG) + self.assertEqual(self.e.containers['another-sidecar']['State']['Status'], 'running') + self.assertFalse((self.source / 'manifest.json').exists()) + + def test_backup_rejects_container_using_only_a_subdirectory_of_its_project_volume(self): + self.e.stack(('host',)) + c = self.e.containers['demo-host'] + c['HostConfig'] = {'Mounts': [{'Type': 'volume', 'Target': '/data', 'Source': 'demo_host-data', + 'VolumeOptions': {'Subpath': 'other-instance'}}]} + with self.assertRaisesRegex(ValueError, 'subdirectory'): + backup.backup(PROJECT, self.source, HOST_TAG) + self.assertFalse(self.source.exists()); self.assertEqual(c['State']['Status'], 'running') + self.assertFalse(any(cmd[0] in ('pause', 'run') for cmd in self.e.calls)) + + def test_backup_reads_containers_without_host_config_mounts_or_volume_options(self): + # Compose 2.40 writes Binds, leaving no HostConfig.Mounts; --mount without options leaves no VolumeOptions. + self.e.stack() + self.e.containers['demo-box']['HostConfig'] = {'Mounts': [{'Type': 'volume', 'Target': '/workspace', + 'Source': 'demo_box-workspace'}]} + backup.backup(PROJECT, self.source, HOST_TAG) + manifest = json.loads((self.source / 'manifest.json').read_text()) + self.assertEqual(len(manifest['volumes']), 3) + self.assertEqual({c['State']['Status'] for c in self.e.containers.values()}, {'running'}) + + def test_box_gets_only_the_five_parent_data_trees_and_host_data_is_archived_once(self): + self.e.stack() + self.add_box_data_mounts() + services = backup.project_services(PROJECT, ('host', 'box'), host_data=True) + self.assertEqual(set(services), {'host', 'box'}) + backup.backup(PROJECT, self.source, HOST_TAG) + manifest = json.loads((self.source/'manifest.json').read_text()) + self.assertEqual([item['suffix'] for item in manifest['volumes']], ['box-home', 'box-workspace', 'host-data']) + self.assertNotIn('connector-secrets', backup.BOX_DATA_TARGETS) + self.assertNotIn('projects', backup.DATA_TREES) + self.assertEqual(len(backup.BOX_DATA_TARGETS), 5) + + def test_fnOS_style_box_bind_tree_mounts_are_accepted(self): + self.e.stack() + self.add_box_data_mounts(bind=True) + services = backup.project_services(PROJECT, ('host', 'box'), host_data=True) + self.assertEqual(set(services), {'host', 'box'}) + for tree in backup.DATA_TREES: + sources = {next(m['Source'] for m in services['box']['Mounts'] + if m['Destination'] == str(root/tree)) for root in backup.BOX_DATA_ROOTS} + self.assertEqual(len(sources), 1) + + def test_partial_extra_wrong_and_read_only_box_data_mounts_are_rejected(self): + self.e.stack() + self.add_box_data_mounts() + box = self.e.containers[PROJECT+'-box'] + original = box['Mounts'] + with self.subTest('partial'): + box['Mounts'] = original[:-1] + with self.assertRaisesRegex(ValueError, 'incomplete'): + backup.project_services(PROJECT, ('host', 'box'), host_data=True) + box['Mounts'] = [dict(item) for item in original] + for name in ('connector-secrets', 'agent-transcripts'): + with self.subTest('sensitive-extra', name=name): + box['Mounts'] = [dict(item) for item in original] + box['Mounts'].append({'Type': 'bind', 'Source': f'/srv/prokbot/runtime/host-data/{name}', + 'Destination': f'/data/runtime/host-data/{name}', 'RW': True}) + with self.assertRaisesRegex(ValueError, 'unapproved'): + backup.project_services(PROJECT, ('host', 'box'), host_data=True) + box['Mounts'] = [dict(item) for item in original] + with self.subTest('wrong-source'): + box['Mounts'][2]['Name'] = 'another_host-data' + with self.assertRaisesRegex(ValueError, 'expected Host-data tree'): + backup.project_services(PROJECT, ('host', 'box'), host_data=True) + box['Mounts'] = [dict(item) for item in original] + with self.subTest('read-only'): + next(item for item in box['Mounts'] if item['Destination'] == '/data/runtime/host-data/agents')['RW'] = False + with self.assertRaisesRegex(ValueError, 'not writable'): + backup.project_services(PROJECT, ('host', 'box'), host_data=True) + box['Mounts'] = [dict(item) for item in original] + with self.subTest('wrong-subpath'): + box['HostConfig']['Mounts'][0]['VolumeOptions']['Subpath'] = 'runtime/host-data/connector-secrets' + with self.assertRaisesRegex(ValueError, 'expected Host-data tree'): + backup.project_services(PROJECT, ('host', 'box'), host_data=True) + + def test_backup_does_not_unpause_prepaused_or_start_stopped_services(self): + self.e.stack() + self.e.docker(['pause', 'demo-box']) + self.e.docker(['stop', 'demo-host']) + backup.backup(PROJECT, self.source, HOST_TAG) + self.assertEqual(self.e.containers['demo-box']['State']['Status'], 'paused') + self.assertEqual(self.e.containers['demo-host']['State']['Status'], 'exited') + self.assertTrue((self.source / 'manifest.json').is_file()) + + def test_resume_attempts_every_container_paused_by_backup(self): + self.e.stack() + self.e.fail = lambda cmd: cmd == ['unpause', 'demo-box'] + with self.assertRaisesRegex(RuntimeError, 'demo-box'): + backup.backup(PROJECT, self.source, HOST_TAG) + self.assertEqual([c[-1] for c in self.e.calls if c[0] == 'unpause'], ['demo-box', 'demo-host']) + self.assertFalse((self.source / 'manifest.json').exists()) + + def test_lost_pause_acknowledgement_does_not_strand_running_service(self): + self.e.stack() + command = self.e.docker + def uncertain(cmd, **kw): + result = command(cmd, **kw) + if list(cmd) == ['pause', 'demo-box']: self.e.error(cmd) + return result + with patch.object(self.e, 'docker', uncertain), self.assertRaises(subprocess.CalledProcessError): + backup.backup(PROJECT, self.source, HOST_TAG) + self.assertTrue(all(c['State']['Status'] == 'running' for c in self.e.containers.values())) + self.assertFalse((self.source / 'manifest.json').exists()) + + def test_live_mounts_not_just_project_volume_names_are_checked(self): + self.invoke('init') + self.e.stack() + self.e.containers['demo-host']['Mounts'] = [{'Type': 'bind', 'Source': '/fixture', 'Destination': '/data', 'RW': True}] + with self.assertRaisesRegex(ValueError, 'mount|volume'): + self.invoke('update') + self.assertFalse(any(cmd[0] in ('build', 'stop', 'pause') or 'up' in cmd for cmd in self.e.calls)) + + def test_failed_switch_keeps_latest_backup_and_stops_candidate(self): + self.invoke('init') + self.e.stack() + data = self.restored(PROJECT, 'host-data') + self.e.after_build = lambda: (data / 'payload').write_bytes(b'last acknowledged write') + self.e.unhealthy = True + with self.assertRaises((ValueError, RuntimeError, subprocess.CalledProcessError)): + self.invoke('update') + self.assertTrue(all(c['State']['Status'] == 'exited' for c in self.e.containers.values()), 'failed candidate still writing') + snapshots = list((self.home / 'backups').glob('*/manifest.json')) + self.assertEqual(len(snapshots), 1) + backup.restore(snapshots[0].parent, 'recovered', HOST_TAG) + recovered = self.restored('recovered', 'host-data') + self.assertEqual((recovered / 'payload').read_bytes(), b'last acknowledged write') + self.assertFalse((recovered / 'partial-migration').exists()) + self.assertTrue((data / 'partial-migration').exists(), 'do not overwrite the live volume to roll back') + self.assertIn(OLD, [v for k, v in self.e.images.items() if k.startswith('prokbot-recovery:')]) + + def test_first_install_health_failure_stops_partial_stack_and_retains_its_volumes(self): + self.invoke('init') + self.e.unhealthy = True + with self.assertRaises((RuntimeError, subprocess.CalledProcessError)): self.invoke('up') + self.assertTrue(all(c['State']['Status'] == 'exited' for c in self.e.containers.values())) + self.assertEqual(len(self.e.labels), 3) + self.assertTrue((self.restored(PROJECT, 'host-data')/'partial-migration').exists()) + with self.assertRaises(ValueError): self.invoke('up') + + def test_failed_candidate_stop_does_not_claim_rollback_or_shutdown(self): + self.invoke('--host-only', 'init') + self.e.stack(('host',)) + self.e.unhealthy = True + self.e.fail = lambda c: c[0] == 'compose' and 'stop' in c + with self.assertRaisesRegex(RuntimeError, 'shutdown NOT confirmed'): self.invoke('update') + self.assertTrue(list((self.home / 'backups').glob('*/manifest.json'))) + self.assertFalse(any(c[0] == 'start' for c in self.e.calls)) + + def test_failed_build_or_platform_check_leaves_old_image_and_processes_alone(self): + self.invoke('--host-only', 'init') + self.e.stack(('host',)) + for mock in (patch.object(deploy, 'build', side_effect=ValueError('build')), + patch.object(deploy, 'docker_platform', return_value='linux/arm64')): + with mock, self.assertRaises(ValueError): self.invoke('update') + self.assertEqual(self.e.images[HOST_TAG], OLD) + self.assertFalse(any(c[0] in ('start', 'stop', 'pause') or 'up' in c for c in self.e.calls)) + + def test_stop_failure_recovers_original_running_services_and_never_starts_candidate(self): + self.invoke('init') + self.e.stack() + self.e.fail = lambda c: c == ['stop', 'demo-box'] + with self.assertRaises(subprocess.CalledProcessError): self.invoke('update') + self.assertTrue(all(c['State']['Status'] == 'running' and c['Image'] != NEW for c in self.e.containers.values())) + self.assertFalse(any('up' in c for c in self.e.calls)) + + def test_backup_failure_resumes_only_originally_running_services(self): + self.invoke('init') + self.e.stack() + self.e.docker(['stop', 'demo-box']) + self.e.fail = lambda c: c[0] == 'run' and '-czf' in c + with self.assertRaises(subprocess.CalledProcessError): self.invoke('update') + self.assertEqual(self.e.images[HOST_TAG], OLD) + self.assertEqual(self.e.containers['demo-host']['State']['Status'], 'running') + self.assertEqual(self.e.containers['demo-box']['State']['Status'], 'exited') + self.assertFalse(any('up' in c for c in self.e.calls)) + + def test_build_time_mount_change_aborts_before_stopping_services(self): + self.invoke('init') + self.e.stack() + self.e.after_build = lambda: self.e.containers['demo-box']['Mounts'].pop() + with self.assertRaisesRegex(ValueError, 'volume'): self.invoke('update') + self.assertFalse(any(c[0] == 'stop' or 'up' in c for c in self.e.calls)) + + def test_mutating_commands_in_same_instance_directory_are_serialized(self): + self.invoke('init') + self.e.stack() + def concurrent_backup(): + with self.assertRaisesRegex(ValueError, 'operation'): self.invoke('backup') + self.e.after_build = concurrent_backup + self.invoke('update') + self.assertEqual(len(list((self.home/'backups').glob('*/manifest.json'))), 1) + + def test_upgrade_cannot_silently_create_an_empty_replacement_volume(self): + self.invoke('init') + self.e.stack() + self.e.before_up = lambda: self.e.labels.pop('demo_host-data') + with self.assertRaisesRegex(RuntimeError, 'No automatic data rollback'): self.invoke('update') + self.assertNotIn('demo_host-data', self.e.labels) + self.assertTrue(list((self.home / 'backups').glob('*/manifest.json'))) + self.assertTrue(all(c['State']['Status'] == 'exited' for c in self.e.containers.values())) + + def test_partial_and_foreign_volumes_block_up_and_update(self): + self.invoke('init') + self.e.volume('demo_host-data', {}) + for action in ('up', 'update'): + with self.assertRaises(ValueError): self.invoke(action) + self.assertFalse(any(c[0] == 'build' for c in self.e.calls)) + + def test_volume_only_host_never_treats_mutable_tag_as_the_previous_image(self): + self.invoke('--host-only', 'init') + self.e.stack(('host',)) + self.e.containers.clear() + self.e.images[HOST_TAG] = NEW + with self.assertRaisesRegex(ValueError, 'volume-only'): self.invoke('update') + self.assertFalse(list((self.home / 'backups').glob('*/manifest.json'))) + self.assertFalse(any(c[0] in ('build', 'stop', 'start') or 'up' in c for c in self.e.calls)) + + def test_unmanaged_submount_blocks_backup_and_update_before_stopping_host(self): + self.invoke('--host-only', 'init') + self.e.stack(('host',)) + uploads = self.e.volume('user-uploads') / 'payload' + uploads.write_bytes(b'private fixture') + self.e.containers['demo-host']['Mounts'].append({'Type':'volume', 'Name':'user-uploads', 'Destination':'/data/uploads', 'RW':True}) + for action in ('backup', 'update'): + with self.assertRaisesRegex(ValueError, '/data/uploads'): self.invoke(action) + self.assertFalse(any(c[0] in ('build', 'stop', 'pause') or 'up' in c for c in self.e.calls)) + self.assertEqual(uploads.read_bytes(), b'private fixture') + + def test_same_daemon_project_cannot_switch_twice_from_different_homes(self): + self.invoke('--host-only', 'init') + other = ['--home', str(self.home.parent/'second-home'), '--project', PROJECT, '--host-only'] + deploy.main([*other, 'init']) + self.e.stack(('host',)) + def concurrent(): + self.e.before_up = lambda: None + with self.assertRaisesRegex(ValueError, 'operation'): deploy.main([*other, 'update']) + self.e.before_up = concurrent + self.invoke('update') + self.assertEqual(sum(c[0] == 'build' for c in self.e.calls), 1) + self.assertEqual(self.e.containers['demo-host']['Image'], NEW) + self.assertEqual(self.e.containers['demo-host']['State']['Status'], 'running') + + def test_lost_image_tag_reply_restores_actual_previous_public_tag_and_original_host(self): + self.invoke('--host-only', 'init') + self.e.stack(('host',)) + previous_tag = 'sha256:' + '4'*64 # Shared tag need not match the running Host. + self.e.images[HOST_TAG] = previous_tag + self.e.image_ids.add(previous_tag) + command = self.e.docker + def uncertain(cmd, **kw): + result = command(cmd, **kw) + if list(cmd) == ['image', 'tag', NEW, HOST_TAG]: self.e.error(cmd) + return result + with patch.object(self.e, 'docker', uncertain), self.assertRaises(subprocess.CalledProcessError): self.invoke('update') + self.assertEqual(self.e.images[HOST_TAG], previous_tag) + self.assertEqual(self.e.containers['demo-host']['Image'], OLD) + self.assertEqual(self.e.containers['demo-host']['State']['Status'], 'running') + self.assertFalse(any('up' in c for c in self.e.calls)) + + def test_new_and_existing_stacks_use_pinned_box_despite_retag_during_start(self): + self.invoke('init') + for action in ('up', 'update'): + self.e.images[BOX_TAG] = BOX + self.e.before_up = lambda: self.e.images.update({BOX_TAG: 'sha256:'+'4'*64}) + self.invoke(action) + self.assertEqual(self.e.containers['demo-box']['Image'], BOX) + + def test_running_wrong_box_image_is_not_reported_as_success(self): + self.invoke('init') + self.e.stack() + command = self.e.docker + def wrong(cmd, **kw): + result = command(cmd, **kw) + if cmd[0] == 'compose' and 'up' in cmd: self.e.containers['demo-box']['Image'] = 'sha256:'+'4'*64 + return result + with patch.object(self.e, 'docker', wrong), self.assertRaisesRegex(RuntimeError, 'verified deployment'): + self.invoke('update') + self.assertTrue(all(c['State']['Status'] == 'exited' for c in self.e.containers.values())) + + def recovery_args(self, split=False): + args = ['--home', str(self.home.parent/'recovery-home'), '--project', 'recovered'] + deploy.main([*args, *(['--host-only'] if split else []), 'init']) + return [*args, 'recover', '--directory', str(self.source)] + + def test_recover_starts_exact_original_images_and_existing_volumes_after_failed_update(self): + self.invoke('init') + self.e.stack() + self.e.unhealthy = True + with self.assertRaises(RuntimeError): self.invoke('update') + self.source = next((self.home/'backups').glob('*/manifest.json')).parent + self.e.unhealthy = False + self.e.images[BOX_TAG] = 'sha256:'+'4'*64 + self.e.images[HOST_TAG] = NEW + args = self.recovery_args() + deploy.main(args) + for service, expected in [('host', OLD), ('box', BOX)]: + self.assertEqual(self.e.containers['recovered-'+service]['Image'], expected) + self.assertEqual(self.e.containers['demo-'+service]['State']['Status'], 'exited') + self.assertFalse((self.restored('recovered', 'host-data')/'partial-migration').exists()) + self.assertTrue((self.restored('demo', 'host-data')/'partial-migration').exists()) + with self.assertRaises(ValueError): deploy.main(args) + + def test_recover_refuses_running_original_missing_image_or_legacy_mutable_manifest(self): + self.snapshot(('host',)) + args = self.recovery_args(split=True) + with self.assertRaisesRegex(ValueError, 'not stopped'): deploy.main(args) + self.e.docker(['stop', 'demo-host']) + path = self.source/'manifest.json' + manifest = json.loads(path.read_bytes()) + self.e.images[HOST_TAG] = NEW + self.e.image_ids.remove(OLD) + with self.assertRaises(subprocess.CalledProcessError): deploy.main(args) + self.e.image_ids.add(OLD) + path.write_text(json.dumps({k:v for k,v in manifest.items() if k != 'serviceImages'})) + with self.assertRaisesRegex(ValueError, 'no verified'): deploy.main(args) + self.assertFalse(any(n.startswith('recovered_') for n in self.e.labels)) + + def test_recover_host_only_requires_stopped_original_and_starts_without_build(self): + self.snapshot(('host',)) + self.e.docker(['stop', 'demo-host']) + args = self.recovery_args(split=True) + deploy.main(args) + self.assertEqual(self.e.containers['recovered-host']['Image'], OLD) + self.assertEqual(self.e.containers['demo-host']['State']['Status'], 'exited') + self.assertFalse(any(c[0] == 'build' for c in self.e.calls)) + + def test_fresh_install_and_existing_update_reuse_data(self): + self.invoke('init') + self.invoke('up') + for suffix in ('host-data', 'box-home', 'box-workspace'): + (self.restored(PROJECT, suffix) / 'payload').write_bytes(suffix.encode()) + self.invoke('update') + for suffix in ('host-data', 'box-home', 'box-workspace'): + self.assertEqual((self.restored(PROJECT, suffix) / 'payload').read_bytes(), suffix.encode()) + self.assertEqual(len(list((self.home / 'backups').glob('*/manifest.json'))), 1) + + +if __name__ == '__main__': + with contextlib.redirect_stdout(io.StringIO()): + unittest.main() diff --git a/host/tests/device-kind.test.mjs b/host/tests/device-kind.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f47da867dc69bc8e2cf00790ee41506225f88ded --- /dev/null +++ b/host/tests/device-kind.test.mjs @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { Auth } from '../server/auth.mjs'; +import { PushService } from '../server/push-service.mjs'; + +function memory(store) { + store.value = structuredClone(store.initial); + store.mutate = async update => update(store.value); +} + +test('Android pairings do not gain desktop execution rights; display metadata preserves older clients', async () => { + const auth = new Auth('.'); memory(auth.store); + const push = new PushService('.', auth); memory(push.store); + for (const [kind, platform, label] of [['android', 'android', 'android'], ['windows', 'desktop', 'windows'], [undefined, 'desktop', 'desktop']]) { + const { pairingKey } = await auth.createPairing(); + const { token, deviceId } = await auth.pair({ platform: 'desktop', deviceName: 'demo', clientKind: kind, pairingKey }); + assert.equal(auth.authenticate(token).platform, platform); + await push.register(deviceId, { kind: 'desktop', clientKind: kind }); + assert.equal(push.get(deviceId).kind, label); + } +}); diff --git a/host/tests/device-touch.test.mjs b/host/tests/device-touch.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..65b566e5ecf56a7f8c382510dd0dfe8203100cde --- /dev/null +++ b/host/tests/device-touch.test.mjs @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { Auth } from '../server/auth.mjs'; + +test('concurrent requests share the last-seen write, retry I/O failure, and respect revocation', async () => { + const auth = new Auth('.'); + auth.store.value = { devices: [{ id: 'device', lastSeenAt: new Date(0).toISOString() }] }; + let writes = 0, permit, failure = true; + auth.store.mutate = async f => { + writes++; + await new Promise(r => { permit = r; }); + if (failure) throw new Error('I/O failure'); + f(auth.store.value); + }; + const batch = Promise.allSettled(Array.from({ length: 100 }, () => auth.touch('device'))); + assert.equal(writes, 1); + permit(); assert.ok((await batch).every(s => s.status === 'rejected')); + failure = false; + const retry = auth.touch('device'); permit(); await retry; + await auth.touch('device'); assert.equal(writes, 2); + auth.store.value.devices[0].lastSeenAt = new Date(0).toISOString(); + const pending = auth.touch('device'); auth.store.value.devices[0].revokedAt = 'revoked'; + permit(); await pending; + assert.equal(auth.store.value.devices[0].lastSeenAt, new Date(0).toISOString()); +}); diff --git a/host/tests/host-summarize.test.mjs b/host/tests/host-summarize.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9fc04c91e87f245cf33b8fcc745a0f2937e7098f --- /dev/null +++ b/host/tests/host-summarize.test.mjs @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { summarizeAgent } from '../runtime/host-summarize.mjs'; + +function fixture({ running = false, runResult = {}, runError } = {}) { + const agentId = '7bbf2710-6f8d-4393-a952-7c6392719ff6'; + const session = { id: agentId }, calls = []; + const original = async () => ({ action: 'original' }); + const runner = { + promptGlue: { assembleTurnAction: original }, + async run(prompt, options) { + calls.push({ type: 'run', prompt, options, action: await this.promptGlue.assembleTurnAction({}) }); + if (runError) throw runError; + return runResult; + }, + }; + const lifecycle = { + inFlightRunCounts: new Map(running ? [[session, 1]] : []), + runningAgentIds() { return new Set([...this.inFlightRunCounts.keys()].map(item => item.id)); }, + beginSessionRun(value) { calls.push({ type: 'begin', session: value }); this.inFlightRunCounts.set(value, 1); }, + endSessionRun(value) { calls.push({ type: 'end', session: value }); this.inFlightRunCounts.delete(value); }, + async enqueueExclusiveRun(id, task, options) { calls.push({ type: 'enqueue', id, options }); return task(); }, + }; + const host = { transcript: { + listAgentsSync: () => [{ id: agentId, name: '测试 Bot', isGroup: false }], + sessions: { resolveBackgroundSession: async id => { calls.push({ type: 'resolve', id }); return session; } }, + runnerRegistry: { getRunner: value => { calls.push({ type: 'runner', session: value }); return runner; } }, + runLifecycle: lifecycle, + roster: { emitAgentUpdate: async id => { calls.push({ type: 'update', id }); } }, + } }; + // The actual Host public library exports neither generated action constructor. + return { agentId, host, library: {}, runner, original, lifecycle, calls }; +} + +test('manual summarization runs the native summarizeAction and restores prompt glue', async () => { + const value = fixture(); + const result = await summarizeAgent(value.host, value.library, value.agentId); + assert.deepEqual(result, { ok: true, agentId: value.agentId, status: 'completed' }); + const run = value.calls.find(item => item.type === 'run'); + assert.match(run.prompt, /conversation summary/); + assert.deepEqual(run.options, { hidden: true, requestSource: 'event', advanceChainOnDelivery: false }); + assert.equal(run.action.action.action.case, 'summarizeAction'); + assert.deepEqual(run.action.action.action.value, {}); + assert.equal(value.runner.promptGlue.assembleTurnAction, value.original); + assert.equal(value.lifecycle.inFlightRunCounts.size, 0); + assert.deepEqual(value.calls.filter(item => item.type === 'enqueue')[0].options, { lane: 'background', source: 'manual-summary' }); +}); + +test('manual summarization refuses a Bot with an active run', async () => { + const value = fixture({ running: true }); + await assert.rejects(summarizeAgent(value.host, value.library, value.agentId), error => error.status === 409); + assert.equal(value.calls.some(item => item.type === 'runner'), false); + assert.equal(value.calls.some(item => item.type === 'begin'), false); +}); + +test('manual summarization restores prompt glue and lifecycle state after failure', async () => { + const failure = new Error('upstream unavailable'), value = fixture({ runError: failure }); + await assert.rejects(summarizeAgent(value.host, value.library, value.agentId), failure); + assert.equal(value.runner.promptGlue.assembleTurnAction, value.original); + assert.equal(value.lifecycle.inFlightRunCounts.size, 0); + assert.equal(value.calls.filter(item => item.type === 'end').length, 1); + assert.equal(value.calls.filter(item => item.type === 'update').length, 1); +}); + +test('an interrupted manual summary does not report completion', async () => { + const value = fixture({ runResult: { aborted: true } }); + await assert.rejects(summarizeAgent(value.host, value.library, value.agentId), error => error.status === 409); + assert.equal(value.runner.promptGlue.assembleTurnAction, value.original); + assert.equal(value.lifecycle.inFlightRunCounts.size, 0); +}); diff --git a/host/tests/media-web.test.mjs b/host/tests/media-web.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0ff24f9d135b6a734f2ba3f97ddc7635d6795935 --- /dev/null +++ b/host/tests/media-web.test.mjs @@ -0,0 +1,148 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { mediaInput, sizeForAspect, submitMedia } from '../server/media-providers.mjs'; +import { describeMediaModels } from '../server/media-settings.mjs'; +import { WebServices } from '../runtime/web-services.mjs'; + +const json = (status, value) => new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } }); +/** Replace global fetch for one test; returns the recorded requests. */ +function stubFetch(t, replies) { + const original = globalThis.fetch, requests = []; + globalThis.fetch = async (url, options) => { requests.push({ url, options }); return replies.shift()(); }; + t.after(() => { globalThis.fetch = original; }); + return requests; +} +const flexible = ['auto', '1024x1024', '1536x1024', '1024x1536', '1536x1152', '1152x1536', '1536x864', '864x1536']; +const imageSchema = { type: 'object', additionalProperties: false, properties: { + prompt: { type: 'string' }, images: { type: 'array', items: { type: 'string' }, maxItems: 10 }, + size: { type: 'string', enum: flexible }, quality: { type: 'string', enum: ['auto', 'low', 'medium', 'high'] } } }; + +test('aspect ratios map to the closest listed size', () => { + assert.equal(sizeForAspect('1:1'), '1024x1024'); + assert.equal(sizeForAspect('16:9'), '1536x1024'); + assert.equal(sizeForAspect('3:4'), '1024x1536'); + assert.equal(sizeForAspect('16:9', flexible), '1536x864'); + assert.equal(sizeForAspect('4:3', flexible), '1536x1152'); + assert.equal(sizeForAspect('9:16', flexible), '864x1536'); + assert.throws(() => sizeForAspect('0:1'), /Invalid aspect ratio/); +}); + +test('OpenAI image models receive a size instead of aspect_ratio', () => { + const plain = { parameters: { size: '1024x1024' } }; + assert.deepEqual(mediaInput(plain, { prompt: 'cat', aspectRatio: '16:9' }, 'openai-images'), { size: '1536x1024', prompt: 'cat' }); + const listed = { parameters: { size: '1024x1024', quality: 'high' }, inputSchema: imageSchema }; + assert.equal(mediaInput(listed, { prompt: 'cat', aspectRatio: '9:16' }, 'openai-images').size, '864x1536'); + // An explicit size from the model wins over the ratio. + assert.equal(mediaInput(listed, { prompt: 'cat', aspectRatio: '9:16', parameters: { size: '1024x1024' } }, 'openai-images').size, '1024x1024'); + // Schemas that accept aspect_ratio keep it unchanged. + const ratio = { parameters: {}, inputSchema: { type: 'object', properties: { prompt: { type: 'string' }, aspect_ratio: { type: 'string' } } } }; + assert.deepEqual(mediaInput(ratio, { prompt: 'cat', aspectRatio: '4:3' }, 'wavespeed'), { prompt: 'cat', aspect_ratio: '4:3' }); + assert.throws(() => mediaInput(listed, { prompt: 'cat', parameters: { size: '777x777' } }, 'openai-images'), /Invalid input.size/); +}); + +test('reference images use the OpenAI edits endpoint', async t => { + const requests = stubFetch(t, [() => json(200, { data: [{ b64_json: 'aGVsbG8=' }] })]); + const model = { model: 'gpt-image-x', parameters: { size: '1024x1024', quality: 'high' }, inputSchema: imageSchema }; + const body = mediaInput(model, { prompt: 'add a hat', aspectRatio: '1:1', + references: [{ mimeType: 'image/png', data: 'iVBORw0KGgo=' }, { mimeType: 'image/jpeg', data: '/9j/4AAQ' }] }, 'openai-images'); + const result = await submitMedia({ adapter: 'openai-images', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }, model, body); + assert.equal(requests[0].url, 'https://api.example.com/v1/images/edits'); + const form = requests[0].options.body; + assert.ok(form instanceof FormData); + assert.equal(requests[0].options.headers['content-type'], undefined); + assert.deepEqual([form.get('model'), form.get('prompt'), form.get('size'), form.get('quality'), form.get('n')], + ['gpt-image-x', 'add a hat', '1024x1024', 'high', '1']); + const files = form.getAll('image[]'); + assert.deepEqual(files.map(file => [file.name, file.type]), [['reference-1.png', 'image/png'], ['reference-2.jpeg', 'image/jpeg']]); + assert.deepEqual(result, { status: 'completed', outputs: [{ base64: 'aGVsbG8=', mimeType: 'image/png' }] }); +}); + +test('text-only prompts use the generations endpoint', async t => { + const requests = stubFetch(t, [() => json(200, { data: [{ b64_json: 'aGVsbG8=' }] })]); + const model = { model: 'gpt-image-x', parameters: {} }; + await submitMedia({ adapter: 'openai-images', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }, model, + mediaInput(model, { prompt: 'cat', aspectRatio: '3:4' }, 'openai-images')); + assert.equal(requests[0].url, 'https://api.example.com/v1/images/generations'); + assert.deepEqual(JSON.parse(requests[0].options.body), { prompt: 'cat', size: '1024x1536', model: 'gpt-image-x', n: 1 }); +}); + +test('reference keys are not advertised as model parameters', () => { + const text = describeMediaModels([{ id: 'img', name: 'Image', description: 'd', parameters: {}, inputSchema: imageSchema }]); + assert.match(text, /"size"/); + assert.doesNotMatch(text, /"images"/); +}); + +test('Anthropic web tools fall back to automatic tool choice', async t => { + const directory = await mkdtemp(join(tmpdir(), 'web-test-')); + t.after(() => rm(directory, { recursive: true, force: true })); + await writeFile(join(directory, 'web-services.json'), JSON.stringify({ version: 1, models: [], defaults: { search: 'a', fetch: 'a' }, + providers: [{ id: 'a', name: 'A', adapter: 'anthropic-tools', baseUrl: 'https://api.example.com/v1', apiKey: 'k', enabled: true, model: 'thinking-model' }] })); + const found = () => json(200, { content: [{ type: 'server_tool_use' }, + { type: 'web_search_tool_result', content: [{ type: 'web_search_result', title: 'Source', url: 'https://example.com/a' }] }, + { type: 'text', text: 'Answer' }] }); + const requests = stubFetch(t, [ + () => json(400, { error: { type: 'invalid_request_error', message: 'this model does not accept a forced tool choice (tool_choice type tool)' } }), + found, found]); + const web = new WebServices(directory); + const result = await web.invoke('search', 'news'); + assert.deepEqual(result, { answer: 'Answer', documents: [{ title: 'Source', url: 'https://example.com/a', text: '' }] }); + const choices = requests.map(request => JSON.parse(request.options.body).tool_choice); + assert.deepEqual(choices, [{ type: 'tool', name: 'web_search' }, { type: 'auto' }]); + await web.invoke('search', 'more news'); + assert.deepEqual(JSON.parse(requests[2].options.body).tool_choice, { type: 'auto' }); +}); + +test('concurrent Anthropic web calls each retry their own forced request', async t => { + const directory = await mkdtemp(join(tmpdir(), 'web-test-')); + t.after(() => rm(directory, { recursive: true, force: true })); + await writeFile(join(directory, 'web-services.json'), JSON.stringify({ version: 1, models: [], defaults: { search: 'a', fetch: 'a' }, + providers: [{ id: 'a', name: 'A', adapter: 'anthropic-tools', baseUrl: 'https://api.example.com/v1', apiKey: 'k', enabled: true, model: 'concurrent-model' }] })); + const original = globalThis.fetch, bodies = []; + t.after(() => { globalThis.fetch = original; }); + globalThis.fetch = async (_url, options) => { + const body = JSON.parse(options.body); bodies.push(body); + if (body.tool_choice.type === 'tool') { + // Both forced requests are in flight before either rejection is processed. + await new Promise(resolve => setTimeout(resolve, bodies.length === 1 ? 20 : 5)); + return json(400, { error: { message: 'does not accept a forced tool choice' } }); + } + const name = body.tools[0].name; + return json(200, { content: [{ type: `${name}_tool_result`, content: name === 'web_search' + ? [{ type: 'web_search_result', title: 'S', url: 'https://example.com/s' }] + : { type: 'web_fetch_result', content: { source: { data: 'page text' } } } }, { type: 'text', text: 'ok' }] }); + }; + const web = new WebServices(directory); + const [search, page] = await Promise.all([web.invoke('search', 'news'), web.invoke('fetch', 'https://example.com/')]); + assert.equal(search.documents.length, 1); + assert.equal(page.content, 'page text'); + assert.equal(bodies.filter(body => body.tool_choice.type === 'auto').length, 2); +}); + +test('Anthropic web search keeps successful calls when a parallel call exceeds max_uses', async t => { + const directory = await mkdtemp(join(tmpdir(), 'web-test-')); + t.after(() => rm(directory, { recursive: true, force: true })); + await writeFile(join(directory, 'web-services.json'), JSON.stringify({ version: 1, models: [], defaults: { search: 'a', fetch: 'a' }, + providers: [{ id: 'a', name: 'A', adapter: 'anthropic-tools', baseUrl: 'https://api.example.com/v1', apiKey: 'k', enabled: true, model: 'parallel-model' }] })); + stubFetch(t, [() => json(200, { content: [{ type: 'server_tool_use' }, { type: 'server_tool_use' }, + { type: 'web_search_tool_result', content: [{ type: 'web_search_result', title: 'Hit', url: 'https://example.com/hit' }] }, + { type: 'web_search_tool_result', content: { type: 'web_search_tool_result_error', error_code: 'max_uses_exceeded' } }, + { type: 'text', text: 'Found it' }] }), + () => json(200, { content: [{ type: 'web_search_tool_result', content: { type: 'web_search_tool_result_error', error_code: 'unavailable' } }] })]); + const web = new WebServices(directory); + assert.deepEqual(await web.invoke('search', 'news'), + { answer: 'Found it', documents: [{ title: 'Hit', url: 'https://example.com/hit', text: '' }] }); + await assert.rejects(web.invoke('search', 'news'), /Native web search failed/); +}); + +test('other Anthropic web tool errors are not retried', async t => { + const directory = await mkdtemp(join(tmpdir(), 'web-test-')); + t.after(() => rm(directory, { recursive: true, force: true })); + await writeFile(join(directory, 'web-services.json'), JSON.stringify({ version: 1, models: [], defaults: { search: 'a', fetch: 'a' }, + providers: [{ id: 'a', name: 'A', adapter: 'anthropic-tools', baseUrl: 'https://api.example.com/v1', apiKey: 'k', enabled: true, model: 'other-model' }] })); + const requests = stubFetch(t, [() => json(400, { error: { message: 'invalid model' } })]); + await assert.rejects(new WebServices(directory).invoke('fetch', 'https://example.com/'), /HTTP 400/); + assert.equal(requests.length, 1); +}); diff --git a/host/tests/memory-extraction-fixture.mjs b/host/tests/memory-extraction-fixture.mjs new file mode 100644 index 0000000000000000000000000000000000000000..949ecba545cedc95a5b8ed4d1539e526abfff7ac --- /dev/null +++ b/host/tests/memory-extraction-fixture.mjs @@ -0,0 +1,116 @@ +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { basename, dirname, join, resolve } from 'node:path'; +import { setImmediate as tick } from 'node:timers/promises'; +import { fileURLToPath } from 'node:url'; +import { createModelSession } from '../runtime/model-session.mjs'; +import { constructRecoveredHostFlow, installRecoveredHostFlow } from '../runtime/recovered-host-flow.mjs'; + +// A project-owned factory and text-only consumer so CI needs no generated Host files. +export function createRecoveredModule({ runTurnMemory }) { return { finishMemory: runTurnMemory }; } + +async function textOnlyTurn(store, _progress, session, ctx, _time, exchange) { + if (store.recordMemoryEvidence) return store.recordMemoryEvidence(exchange); + try { + const executor = session.getExecutor(); + executor.appendMessages({ role: 'user', content: exchange.user }); + const parts = await Array.fromAsync(executor.stream(ctx).fullStream); + store.addMemory(parts.filter(part => part.type === 'text-delta').map(part => part.textDelta).join('')); + } catch { /* The upstream collector treats extraction as best effort. */ } +} + +// Like the Host usage middleware, expose new promises *after* the adapter guarded its own. +const derived = ['response', 'usage', 'extendedUsage']; +function withDerivedResults(session) { + return { getExecutor() { + const executor = session.getExecutor(); + return { + appendMessages: messages => executor.appendMessages(messages), + stream(...args) { + const result = executor.stream(...args); + return { ...result, ...Object.fromEntries(derived.map(key => [key, result[key].then(value => value)])) }; + }, + }; + } }; +} + +const chunk = text => `data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\n`; +const completion = 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n'; +function resetReply() { + return new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(chunk('incomplete fact'))); }, + pull(controller) { + const cause = Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }); + controller.error(new TypeError('private provider detail', { cause })); + }, + }, { highWaterMark: 0 })); +} + +export async function exerciseMemory(finishTurn, sanitize, mode) { + let requests = 0; + const saved = []; + const store = { recall: () => ({ profile: [], recent: [] }), listMemories: () => [], + addMemory: content => saved.push(content) }; + const session = sanitize(createModelSession({ model: 'memory-test', baseUrl: 'https://model.invalid/v1', + async fetchImpl() { + requests++; + if (mode === 'unrelated') { + void Promise.reject(new Error('unrelated rejection during memory extraction')); + await tick(); + } + return requests === 2 ? new Response(chunk('fact from next turn') + completion) : resetReply(); + }, + })); + await finishTurn(store, session); + await tick(); // Allow Node to detect any unread, rejected completion promises. + assert.deepEqual(saved, []); + assert.equal(requests, 1); + await finishTurn(store, session); + await tick(); + assert.deepEqual(saved, ['fact from next turn']); + assert.equal(requests, 2); + + // The shared session must still deliver a foreground failure to every consumer. + const foreground = session.getExecutor().stream({}); + const outcomes = Promise.allSettled(derived.map(key => foreground[key])); + let foregroundError; + await assert.rejects(Array.fromAsync(foreground.fullStream), error => { + foregroundError = error; + return error.cause?.code === 'ECONNRESET'; + }); + for (const outcome of await outcomes) { + assert.equal(outcome.status, 'rejected'); + assert.equal(outcome.reason, foregroundError); + } + const evidenceError = new Error('evidence store failed'); + await assert.rejects(finishTurn({ recordMemoryEvidence() { throw evidenceError; } }, session), + error => error === evidenceError); + assert.equal(requests, 3); + console.log('next memory saved; foreground and evidence errors preserved'); +} + +export async function run(mode, seed) { + if (seed) { + // Optional read-only check with the user's generated bindings, factory and native dependencies. + const library = createRequire(import.meta.url)(resolve(seed, 'host-library.cjs')); + await installRecoveredHostFlow(library, join(seed, 'release-reliability')); + const { createTurnSettle, sanitizePromptSessionUsage } = library.getHarnessRecoveryBindings(); + return exerciseMemory(async (memoryStore, session) => { + const settle = createTurnSettle({ latestPromptMessages: () => [], isRunSuperseded: () => false }, { memoryStore }); + settle.collectors.collectText('completed chat reply'); + await settle.settleCompletedTurn({ session, baseCtx: library.createContext(), finalState: { turnTimings: [] }, + turnStartedAtMs: Date.now(), trimmedPrompt: 'Please remember my preference.', skipLabeling: true }); + assert.equal(settle.buildResult({ aborted: false }).text, 'completed chat reply'); + }, sanitizePromptSessionUsage, mode); + } + const filename = fileURLToPath(import.meta.url); + const dependencies = ['runTurnMemory']; + const library = { + getHostFlowRecoveryBindings: () => ({ runTurnMemory: textOnlyTurn }), + hostFlowRecoveryPlan: { modules: [{ name: basename(filename), exports: ['finishMemory'], + dependencies, originalDependencies: dependencies, recoveredDependencies: [] }] }, + }; + const { bindings } = await constructRecoveredHostFlow(library, dirname(filename)); + await exerciseMemory((store, session) => bindings.finishMemory(store, null, session, {}, Date.now(), + { user: 'Please remember my preference.', agent: 'Noted.' }), withDerivedResults, mode); +} diff --git a/host/tests/memory-extraction.test.mjs b/host/tests/memory-extraction.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e2c6cdb24cf08a4e632372e5d9df5fc47e96d2d3 --- /dev/null +++ b/host/tests/memory-extraction.test.mjs @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import test from 'node:test'; + +function child(mode, policy, seed) { + const fixture = new URL('./memory-extraction-fixture.mjs', import.meta.url); + const result = spawnSync(process.execPath, [`--unhandled-rejections=${policy}`, '--input-type=module', '-e', + 'const fixture = await import(process.argv[1]); await fixture.run(...process.argv.slice(2));', fixture.href, mode, seed], + { encoding: 'utf8', timeout: 15_000, env: { ...process.env, SAND_DISABLE_ANALYTICS: '1', SAND_DISABLE_TELEMETRY: '1' } }); + assert.ifError(result.error); + return result; +} + +const sources = new Map([['portable', '']]); +if (process.env.PROKBOT_TEST_HOST_SEED) sources.set('generated Host', process.env.PROKBOT_TEST_HOST_SEED); +for (const [source, seed] of sources) { + test(`${source}: a post-turn memory reset is reported once and the same child saves the next memory`, () => { + const result = child('recover', 'strict', seed); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /next memory saved; foreground and evidence errors preserved/); + assert.equal(result.stderr.match(/\[memory\]/g)?.length, 1, result.stderr); + assert.match(result.stderr, /ECONNRESET/); + assert.doesNotMatch(result.stderr, /private provider detail|incomplete fact/); + }); + + test(`${source}: an unrelated unhandled rejection during memory extraction is still fatal`, () => { + const result = child('unrelated', 'throw', seed); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /Error: unrelated rejection during memory extraction/); + assert.doesNotMatch(result.stdout, /next memory saved/); + }); +} diff --git a/host/tests/model-fallback.test.mjs b/host/tests/model-fallback.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..292f90fc732856673acefe0a238eb74dbb585ae6 --- /dev/null +++ b/host/tests/model-fallback.test.mjs @@ -0,0 +1,229 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createModelSession } from '../runtime/model-session.mjs'; +import { ModelRequestError } from '../runtime/model-common.mjs'; +import { createHarnessModelErrorMapper } from '../runtime/model-errors.mjs'; + +const done = text => new Response(`data: ${JSON.stringify({ choices: [{ delta: { content: text }, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`); +const toolCall = (id = 'call_1') => new Response(`data: ${JSON.stringify({ choices: [{ delta: { tool_calls: [ + { index: 0, id, function: { name: 'record', arguments: '{}' } }, +] }, finish_reason: 'tool_calls' }] })}\n\ndata: [DONE]\n\n`); +const exhausted = () => new Response(JSON.stringify({ error: { message: 'API key quota exhausted', code: 'API_KEY_QUOTA_EXHAUSTED' } }), { status: 429 }); +const failure = (status, message = `HTTP ${status}`, code) => new Response(JSON.stringify({ error: { message, ...(code ? { code } : {}) } }), { status }); + +function session(fetchImpl, selectRequest, onFallback = async () => {}) { + return createModelSession({ baseUrl: 'https://primary.example/v1', apiKey: 'primary-key', model: 'primary', + fetchImpl, selectRequest, onFallback, idleTimeoutMs: 1_000 }); +} + +test('an exhausted primary switches only to a fallback with independent credentials', async () => { + const requests = [], fallbacks = []; + const model = session(async (url, options) => { + requests.push([url, JSON.parse(options.body).model, options.headers.get('authorization')]); + return requests.length === 1 ? exhausted() : done('recovered'); + }, () => ({ model: 'primary', fallbacks: [{ baseUrl: 'https://backup.example/v1', apiKey: 'backup-key', + apiFormat: 'openai', model: 'backup', providerId: 'backup' }] }), event => fallbacks.push(event)); + const result = model.getExecutor([{ role: 'user', content: 'hello' }]).stream({}, 'test', []); + const parts = await Array.fromAsync(result.fullStream); + assert.deepEqual(parts.filter(part => part.type === 'text-delta').map(part => part.textDelta), ['recovered']); + assert.deepEqual(requests, [ + ['https://primary.example/v1/chat/completions', 'primary', 'Bearer primary-key'], + ['https://backup.example/v1/chat/completions', 'backup', 'Bearer backup-key'], + ]); + assert.equal(fallbacks.length, 1); + assert.equal(fallbacks[0].reason, 'HTTP 429'); +}); + +test('an exhausted primary does not retry a fallback sharing its API key', async () => { + let requests = 0; + const fallbacks = []; + const model = session(async () => { requests++; return exhausted(); }, () => ({ model: 'primary', fallbacks: [ + { baseUrl: 'https://another-gateway.example/v1', apiKey: 'primary-key', apiFormat: 'openai', model: 'other' }, + ] }), event => fallbacks.push(event)); + const result = model.getExecutor([{ role: 'user', content: 'hello' }]).stream({}, 'test', []); + await assert.rejects(Array.fromAsync(result.fullStream), error => { + assert.equal(error.status, 429); + assert.equal(error.code, 'API_KEY_QUOTA_EXHAUSTED'); + return true; + }); + assert.equal(requests, 1); + assert.equal(fallbacks[0].reason, 'quota'); + assert.equal(fallbacks[0].skipped[0].model, 'other'); + assert.equal(JSON.stringify(fallbacks).includes('primary-key'), false); +}); + +test('a transient primary failure retries a fallback sharing its API key', async () => { + const requests = []; + const model = session(async (url, options) => { + requests.push([url, JSON.parse(options.body).model]); + return requests.length === 1 ? failure(503) : done('recovered'); + }, () => ({ model: 'primary', fallbacks: [ + { baseUrl: 'https://same-key.example/v1', apiKey: 'primary-key', apiFormat: 'openai', model: 'other' }, + ] })); + const result = model.getExecutor([{ role: 'user', content: 'hello' }]).stream({}, 'test', []); + const parts = await Array.fromAsync(result.fullStream); + assert.deepEqual(parts.filter(part => part.type === 'text-delta').map(part => part.textDelta), ['recovered']); + assert.deepEqual(requests, [ + ['https://primary.example/v1/chat/completions', 'primary'], + ['https://same-key.example/v1/chat/completions', 'other'], + ]); +}); + +test('a fallback with an independent key can take over an HTTP 402 balance error', async () => { + const requests = []; + const model = session(async (url, options) => { + requests.push([url, JSON.parse(options.body).model]); + return requests.length === 1 ? failure(402, 'Insufficient balance') : done('recovered'); + }, () => ({ model: 'primary', fallbacks: [ + { baseUrl: 'https://backup.example/v1', apiKey: 'backup-key', apiFormat: 'openai', model: 'backup' }, + ] })); + const result = model.getExecutor([{ role: 'user', content: 'hello' }]).stream({}, 'test', []); + const parts = await Array.fromAsync(result.fullStream); + assert.deepEqual(parts.filter(part => part.type === 'text-delta').map(part => part.textDelta), ['recovered']); + assert.equal(requests.length, 2); +}); + +test('a caller-owned timeout is not treated as an upstream idle timeout', async () => { + let requests = 0; + const cancellation = new AbortController(); + const started = Promise.withResolvers(); + const model = session(async () => { + requests++; + started.resolve(); + await new Promise(() => {}); + throw new DOMException('caller deadline', 'TimeoutError'); + }, () => ({ model: 'primary', fallbacks: [ + { baseUrl: 'https://backup.example/v1', apiKey: 'backup-key', apiFormat: 'openai', model: 'backup' }, + ] })); + const result = model.getExecutor([{ role: 'user', content: 'hello' }]).stream({ signal: cancellation.signal }, 'test', []); + const reading = assert.rejects(Array.fromAsync(result.fullStream), { name: 'TimeoutError', message: 'caller deadline' }); + await started.promise; + cancellation.abort(new DOMException('caller deadline', 'TimeoutError')); + await reading; + assert.equal(requests, 1); +}); + +test('cancellation during fallback logging prevents the backup request', async () => { + let requests = 0; + const cancellation = new AbortController(); + const fallbackStarted = Promise.withResolvers(); + const fallbackFinished = Promise.withResolvers(); + const model = createModelSession({ baseUrl: 'https://primary.example/v1', apiKey: 'primary-key', model: 'primary', + fetchImpl: async () => { requests++; return failure(503); }, idleTimeoutMs: 1_000, + selectRequest: async () => ({ model: 'primary', fallbacks: [ + { baseUrl: 'https://backup.example/v1', apiKey: 'backup-key', apiFormat: 'openai', model: 'backup' }, + ] }), + onFallback: async () => { fallbackStarted.resolve(); await fallbackFinished.promise; } }); + const result = model.getExecutor([{ role: 'user', content: 'hello' }]).stream({ signal: cancellation.signal }, 'test', []); + const reading = assert.rejects(Array.fromAsync(result.fullStream), { name: 'AbortError' }); + await fallbackStarted.promise; + cancellation.abort(new DOMException('canceled while logging', 'AbortError')); + fallbackFinished.resolve(); + await reading; + assert.equal(requests, 1); +}); + +test('a tool loop stays on the accepted fallback for its next step', async () => { + const requests = []; + const model = session(async (url, options) => { + const modelId = JSON.parse(options.body).model; + requests.push(modelId); + if (modelId === 'primary') return failure(503); + return requests.length === 2 ? toolCall() : done('complete'); + }, () => ({ model: 'primary', fallbacks: [ + { baseUrl: 'https://backup.example/v1', apiKey: 'backup-key', apiFormat: 'openai', model: 'backup' }, + ] })); + const executor = model.getExecutor([{ role: 'user', content: 'hello' }]); + await Array.fromAsync(executor.stream({}, 'first-step', []).fullStream); + await Array.fromAsync(executor.stream({}, 'second-step', []).fullStream); + assert.deepEqual(requests, ['primary', 'backup', 'backup']); +}); + +test('request and usage metadata come from the model that completed the turn', async () => { + const ids = [], usages = []; + const primaryFailure = new Response(JSON.stringify({ error: { message: 'HTTP 503' } }), { status: 503, + headers: { 'x-request-id': 'failed-primary-id' } }); + const backupSuccess = new Response(`data: ${JSON.stringify({ id: 'successful-backup-id', model: 'backup', + choices: [{ delta: { content: 'recovered' }, finish_reason: 'stop' }], usage: { prompt_tokens: 2, completion_tokens: 3 } })}\n\ndata: [DONE]\n\n`); + const model = createModelSession({ baseUrl: 'https://primary.example/v1', apiKey: 'primary-key', model: 'primary', + idleTimeoutMs: 1_000, onRequestId: id => ids.push(id), onUsage: value => usages.push(value), + fetchImpl: async () => requests++ === 0 ? primaryFailure : backupSuccess, + selectRequest: async () => ({ model: 'primary', fallbacks: [ + { baseUrl: 'https://backup.example/v1', apiKey: 'backup-key', apiFormat: 'openai', model: 'backup', + profileId: 'backup-profile', providerId: 'backup-provider' }, + ] }) }); + let requests = 0; + await Array.fromAsync(model.getExecutor([{ role: 'user', content: 'hello' }]).stream({}, 'test', []).fullStream); + assert.deepEqual(ids, ['successful-backup-id']); + assert.equal(usages.length, 1); + assert.equal(usages[0].model, 'backup'); + assert.equal(usages[0].requestId, 'successful-backup-id'); + assert.equal(usages[0].profileId, 'backup-profile'); + assert.equal(usages[0].providerId, 'backup-provider'); +}); + +test('usage observed before a failed stream remains attributed to that attempt', async () => { + const usages = []; + const failed = new Response(`data: ${JSON.stringify({ id: 'primary-request', model: 'primary-returned', + choices: [{ delta: { reasoning_content: 'partial' }, finish_reason: null }], + usage: { prompt_tokens: 7, completion_tokens: 2 } })}\n\n`); + const model = createModelSession({ baseUrl: 'https://primary.example/v1', apiKey: 'primary-key', model: 'primary', + idleTimeoutMs: 1_000, onUsage: value => usages.push(value), + fetchImpl: async () => usages.length ? done('recovered') : failed, + selectRequest: async () => ({ model: 'primary', profileId: 'primary-profile', providerId: 'primary-provider', fallbacks: [ + { baseUrl: 'https://backup.example/v1', apiKey: 'backup-key', apiFormat: 'openai', model: 'backup', + profileId: 'backup-profile', providerId: 'backup-provider' }, + ] }) }); + await assert.rejects(Array.fromAsync(model.getExecutor([{ role: 'user', content: 'hello' }]).stream({}, 'test', []).fullStream), + /completion marker/); + assert.equal(usages.length, 1); + assert.equal(usages[0].model, 'primary-returned'); + assert.equal(usages[0].requestId, 'primary-request'); + assert.equal(usages[0].profileId, 'primary-profile'); + assert.equal(usages[0].providerId, 'primary-provider'); + assert.equal(usages[0].raw.prompt_tokens, 7); +}); + +test('quota exhaustion maps to a non-retryable Harness error after all routes fail', () => { + class ConnectError extends Error {} + class ActionRequiredError extends Error {} + class NonRetriableError extends Error { + constructor(message, options) { super(message, options); this.displayInfo = options.displayInfo; } + } + const map = createHarnessModelErrorMapper({ ConnectError, ActionRequiredError, NonRetriableError, + Code: { ResourceExhausted: 8, Unavailable: 14, Internal: 13 } }); + const mapped = map(new ModelRequestError('API key quota exhausted', { status: 429, code: 'API_KEY_QUOTA_EXHAUSTED' })); + assert.ok(mapped instanceof NonRetriableError); + assert.equal(mapped.displayInfo.isRetryable, false); +}); + +test('quota-like 429 errors remain retryable unless the API key is explicitly exhausted', () => { + class ConnectError extends Error {} + class ActionRequiredError extends Error {} + class NonRetriableError extends Error {} + const map = createHarnessModelErrorMapper({ ConnectError, ActionRequiredError, NonRetriableError, + Code: { ResourceExhausted: 8, Unavailable: 14, Internal: 13 } }); + for (const message of [ + 'Requests to this model are temporarily over quota; retry later.', + '429 temporary quota exceeded; retry later', + 'temporary quota exhausted; retry later', + ]) { + const mapped = map(new ModelRequestError(message, { status: 429 })); + assert.ok(mapped instanceof ConnectError, message); + } + const permanent = map(new ModelRequestError('429 API key quota exhausted', { status: 429 })); + assert.ok(permanent instanceof NonRetriableError); +}); + +test('a temporary quota 429 still reaches a same-key fallback', async () => { + const requests = []; + const model = session(async (url, options) => { + requests.push(JSON.parse(options.body).model); + return requests.length === 1 ? failure(429, 'temporary quota exceeded; retry later') : done('recovered'); + }, () => ({ model: 'primary', fallbacks: [ + { baseUrl: 'https://same-key.example/v1', apiKey: 'primary-key', apiFormat: 'openai', model: 'other' }, + ] })); + const result = model.getExecutor([{ role: 'user', content: 'hello' }]).stream({}, 'test', []); + await Array.fromAsync(result.fullStream); + assert.deepEqual(requests, ['primary', 'other']); +}); diff --git a/host/tests/model-formats.test.mjs b/host/tests/model-formats.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a441d4effb08653483f001ce56e53c9ec5a47ac3 --- /dev/null +++ b/host/tests/model-formats.test.mjs @@ -0,0 +1,387 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createModelSession } from '../runtime/model-session.mjs'; +import { rejectedOption, deletePath, reasoningProviderOptions } from '../runtime/model-common.mjs'; +import { anthropicEndpoint, anthropicOptions, convertAnthropicMessages } from '../runtime/anthropic-messages.mjs'; +import { convertResponsesInput, responsesOptions } from '../runtime/openai-responses.mjs'; +import { convertChatMessages, maxTokensParameter } from '../runtime/openai-chat.mjs'; +import { effortLevels } from '../runtime/model-policy.mjs'; + +const anthropicTag = model => ({ providerOptions: reasoningProviderOptions({ format: 'anthropic', model }) }); +const responsesTag = (model, itemId) => ({ providerOptions: reasoningProviderOptions({ format: 'openai-responses', model, summarized: true, itemId }) }); +const chatTag = model => ({ providerOptions: reasoningProviderOptions({ format: 'openai', model }) }); + +function sse(events, { done = false } = {}) { + const text = events.map(value => `data: ${JSON.stringify(value)}\n\n`).join('') + (done ? 'data: [DONE]\n\n' : ''); + return new Response(text, { status: 200, headers: { 'content-type': 'text/event-stream', 'x-request-id': 'req_1' } }); +} +const failure = (status, error) => new Response(JSON.stringify({ error }), { status, headers: { 'content-type': 'application/json' } }); + +/** Run one session turn with scripted HTTP responses; returns stream parts, response and requests. */ +async function turn(apiFormat, replies, { model = 'm', effort, messages, tools = [], efforts } = {}) { + const requests = []; + const session = createModelSession({ apiFormat, baseUrl: 'https://api.example.com/v1', apiKey: 'k', model, + policy: efforts ? { models: [{ id: model, efforts }] } : undefined, + fetchImpl: async (url, options) => { requests.push({ url, headers: options.headers, body: JSON.parse(options.body) }); return replies.shift()(); }, + selectRequest: async () => ({ model, effort }) }); + const result = session.getExecutor(messages ?? [{ role: 'user', content: 'Weather in Paris?' }]).stream({}, 'inv', tools); + const parts = []; + for await (const part of result.fullStream) parts.push(part); + return { parts, response: await result.response, usage: await result.usage, requests }; +} +const weatherTool = [{ name: 'get_weather', description: 'Weather', parameters: { type: 'object', properties: { city: { type: 'string' } } } }]; + +// ---- Shared --------------------------------------------------------------------------- + +test('rejected optional parameters are recognized from param or message', () => { + assert.equal(rejectedOption({ status: 400, message: "Unsupported parameter: 'max_tokens' is not supported with this model." }, ['max_tokens', 'stream_options']), 'max_tokens'); + assert.equal(rejectedOption({ status: 400, message: 'bad', param: 'reasoning.summary' }, ['reasoning.summary', 'include']), 'reasoning.summary'); + assert.equal(rejectedOption({ status: 400, message: 'fallbacks: Extra inputs are not permitted' }, ['fallbacks']), 'fallbacks'); + assert.equal(rejectedOption({ status: 429, message: 'max_tokens' }, ['max_tokens']), undefined); + const body = { reasoning: { summary: 'auto' }, include: [] }; + deletePath(body, 'reasoning.summary'); + assert.deepEqual(body, { include: [] }); +}); + +test('effort reference levels include minimal and follow Claude generations', () => { + assert.deepEqual(effortLevels('gpt-5'), ['minimal', 'low', 'medium', 'high']); + assert.deepEqual(effortLevels('claude-opus-5-5'), ['low', 'medium', 'high', 'xhigh', 'max']); + assert.deepEqual(effortLevels('claude-sonnet-5-5'), ['none', 'low', 'medium', 'high', 'xhigh', 'max']); + assert.deepEqual(effortLevels('claude-opus-4-6'), ['none', 'low', 'medium', 'high', 'max']); +}); + +// ---- Anthropic Messages --------------------------------------------------------------- + +test('anthropic endpoint accepts host, /v1 root and full messages URL', () => { + assert.equal(anthropicEndpoint('https://llm.example.com'), 'https://llm.example.com/v1/messages'); + assert.equal(anthropicEndpoint('https://llm.example.com/v1/'), 'https://llm.example.com/v1/messages'); + assert.equal(anthropicEndpoint('https://llm.example.com/v1/messages'), 'https://llm.example.com/v1/messages'); + assert.equal(anthropicEndpoint('https://llm.example.com/v1', 'models'), 'https://llm.example.com/v1/models'); +}); + +test('anthropic effort maps to each Claude generation', () => { + assert.deepEqual(anthropicOptions('claude-opus-5-5', { effort: 'high' }), { max_tokens: 64000, + thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'high' }, fallbacks: 'default' }); + assert.deepEqual(anthropicOptions('claude-opus-5-5', { effort: 'none' }).output_config, { effort: 'low' }); + assert.deepEqual(anthropicOptions('claude-sonnet-5-5', { effort: 'none' }).thinking, { type: 'between_tools' }); + assert.deepEqual(anthropicOptions('claude-opus-4-7', { effort: 'none' }).thinking, { type: 'disabled' }); + assert.deepEqual(anthropicOptions('claude-opus-4-6', { effort: 'xhigh' }).output_config, { effort: 'high' }); + assert.deepEqual(anthropicOptions('claude-opus-4-8', { effort: 'minimal' }).output_config, { effort: 'low' }); + const legacy = anthropicOptions('claude-sonnet-4-5-20250929', { effort: 'high' }); + assert.equal(legacy.thinking.type, 'enabled'); + assert.ok(legacy.thinking.budget_tokens < legacy.max_tokens); + assert.equal(anthropicOptions('claude-haiku-4-5', {}).thinking, undefined); + assert.equal(anthropicOptions('claude-opus-5-5', { maxTokens: 500_000 }).max_tokens, 128000); +}); + +test('anthropic history keeps tool results, screenshots, documents and only Anthropic thinking', () => { + const { system, messages, replayedThinking } = convertAnthropicMessages([ + { role: 'system', content: 'Be helpful.' }, + { role: 'user', content: [{ type: 'text', text: 'Read this' }, { type: 'file', data: 'JVBERg==', mimeType: 'application/pdf', filename: 'a.pdf' }] }, + { role: 'assistant', content: [ + { type: 'reasoning', text: 'Need a screenshot.', signature: 'sig-1', ...anthropicTag('claude-opus-5-5') }, + { type: 'reasoning', text: 'GPT summary', signature: 'enc', ...responsesTag('gpt-5.5', 'rs_1') }, + { type: 'text', text: 'Checking.' }, + { type: 'tool-call', toolCallId: 'toolu_1', toolName: 'screenshot', args: {} }, + ] }, + { role: 'tool', content: [{ type: 'tool-result', toolCallId: 'toolu_1', toolName: 'screenshot', result: undefined, + experimental_content: [{ type: 'text', text: 'captured' }, { type: 'image', data: 'AAAA', mimeType: 'image/png' }] }] }, + { role: 'user', content: 'Thanks' }, + ]); + assert.deepEqual(system, [{ type: 'text', text: 'Be helpful.', cache_control: { type: 'ephemeral' } }]); + assert.equal(replayedThinking, true); + assert.deepEqual(messages[0].content[1], { type: 'document', source: { type: 'base64', media_type: 'application/pdf', data: 'JVBERg==' }, title: 'a.pdf' }); + assert.deepEqual(messages[1].content.map(block => block.type), ['thinking', 'text', 'tool_use']); + assert.equal(messages[2].content[0].type, 'tool_result'); + assert.deepEqual(messages[2].content[0].content[1], { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'AAAA' } }); +}); + +test('anthropic thinking without its signature strips every thinking block', () => { + const { messages, replayedThinking } = convertAnthropicMessages([ + { role: 'user', content: 'a' }, + { role: 'assistant', content: [{ type: 'reasoning', text: 'x', signature: 's', ...anthropicTag('claude-opus-5-5') }, { type: 'text', text: 'b' }] }, + { role: 'user', content: 'c' }, + { role: 'assistant', content: [{ type: 'reasoning', text: 'y', ...anthropicTag('claude-opus-5-5') }, { type: 'text', text: 'd' }] }, + { role: 'user', content: 'e' }, + ]); + assert.equal(replayedThinking, false); + assert.ok(messages.every(item => item.content.every(block => block.type !== 'thinking'))); +}); + +test('anthropic stream yields tagged reasoning, its signature, text, tool call and usage', async () => { + const { parts, response, usage, requests } = await turn('anthropic', [() => sse([ + { type: 'message_start', message: { id: 'msg_1', model: 'claude-opus-5-5', usage: { input_tokens: 10, cache_read_input_tokens: 5, output_tokens: 1 } } }, + { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'Use the tool.' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: 'sig' } }, + { type: 'content_block_stop', index: 0 }, + { type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } }, + { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: 'Checking.' } }, + { type: 'content_block_start', index: 2, content_block: { type: 'tool_use', id: 'toolu_1', name: 'get_weather', input: {} } }, + { type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: '{"city":"Paris"}' } }, + { type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 42 } }, + { type: 'message_stop' }, + ])], { model: 'claude-opus-5-5', effort: 'high', tools: weatherTool }); + assert.equal(requests[0].url, 'https://api.example.com/v1/messages'); + assert.equal(requests[0].headers.get('x-api-key'), 'k'); + assert.equal(requests[0].body.output_config.effort, 'high'); + assert.deepEqual(parts.filter(part => part.type === 'reasoning').map(part => part.textDelta), ['Use the tool.']); + assert.equal(parts.find(part => part.type === 'reasoning').providerOptions.cursor.modelName, 'claude-opus-5-5'); + assert.deepEqual(parts.find(part => part.type === 'reasoning-signature'), { type: 'reasoning-signature', signature: 'sig' }); + assert.deepEqual(parts.find(part => part.type === 'tool-call'), { type: 'tool-call', toolCallId: 'toolu_1', toolName: 'get_weather', args: { city: 'Paris' } }); + assert.equal(parts.at(-1).finishReason, 'tool-calls'); + const reasoning = response.messages[0].content[0]; + assert.equal(reasoning.signature, 'sig'); + assert.equal(reasoning.providerOptions.grokbot.format, 'anthropic'); + assert.deepEqual(usage, { promptTokens: 15, completionTokens: 42, totalTokens: 57 }); +}); + +test('anthropic retries without rejected fallbacks and without stale thinking', async () => { + const done = () => sse([{ type: 'message_start', message: { id: 'm', usage: {} } }, { type: 'content_block_start', index: 0, content_block: { type: 'text', text: 'ok' } }, + { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 1 } }, { type: 'message_stop' }]); + const history = [{ role: 'user', content: 'a' }, { role: 'assistant', content: [{ type: 'reasoning', text: 'x', signature: 's', ...anthropicTag('claude-opus-5-5') }, { type: 'text', text: 'b' }] }, { role: 'user', content: 'c' }]; + const { requests } = await turn('anthropic', [ + () => failure(400, { type: 'invalid_request_error', message: 'fallbacks: Extra inputs are not permitted' }), + () => failure(400, { type: 'invalid_request_error', message: 'messages.1.content.0: Invalid `signature` in `thinking` block.' }), + done, + ], { model: 'claude-opus-5-5', messages: history }); + assert.equal(requests.length, 3); + assert.equal(requests[1].body.fallbacks, undefined); + assert.equal(requests[1].headers.get('anthropic-beta'), null); + assert.ok(requests[1].body.messages[1].content.some(block => block.type === 'thinking')); + assert.ok(requests[2].body.messages[1].content.every(block => block.type !== 'thinking')); +}); + +test('anthropic refusal and truncation surface as model errors', async () => { + const end = reason => () => sse([{ type: 'message_start', message: { id: 'm', usage: {} } }, + { type: 'message_delta', delta: { stop_reason: reason, ...(reason === 'refusal' ? { stop_details: { category: 'cyber' } } : {}) }, usage: { output_tokens: 0 } }, { type: 'message_stop' }]); + await assert.rejects(turn('anthropic', [end('refusal')]), /declined this request \(cyber\)/); + await assert.rejects(turn('anthropic', [end('max_tokens')]), /max_tokens/); +}); + +// ---- OpenAI Responses ----------------------------------------------------------------- + +test('responses options request summaries and encrypted reasoning statelessly', () => { + assert.deepEqual(responsesOptions('gpt-5.5', { effort: 'high' }), { store: false, parallel_tool_calls: true, + reasoning: { effort: 'high', summary: 'auto' }, include: ['reasoning.encrypted_content'] }); + assert.deepEqual(responsesOptions('gpt-5.5', { effort: 'none' }).reasoning, { effort: 'none' }); + assert.equal(responsesOptions('gpt-4.1-mini', { efforts: ['none'] }).reasoning, undefined); + assert.equal(responsesOptions('grok-4.7', { effort: 'minimal', maxTokens: 900 }).max_output_tokens, 900); +}); + +test('responses input keeps instructions, media, phase and own encrypted reasoning in order', () => { + const { instructions, input, replayed } = convertResponsesInput([ + { role: 'system', content: 'Be helpful.' }, + { role: 'user', content: [{ type: 'text', text: 'Look' }, { type: 'image', image: 'QUJD', mimeType: 'image/png' }] }, + { role: 'assistant', content: [ + { type: 'reasoning', text: 'Plan', signature: 'enc-1', ...responsesTag('gpt-5.5', 'rs_1') }, + { type: 'tool-call', toolCallId: 'call_1', toolName: 'screenshot', args: {} }, + { type: 'reasoning', text: 'Claude', signature: 'sig', ...anthropicTag('claude-opus-5-5') }, + { type: 'reasoning', text: 'Other model', signature: 'enc-2', ...responsesTag('gpt-6-sol', 'rs_2') }, + { type: 'text', text: 'Done', providerOptions: { grokbot: { phase: 'final_answer' } } }, + ] }, + { role: 'tool', content: [{ type: 'tool-result', toolCallId: 'call_1', toolName: 'screenshot', result: 'ok', + experimental_content: [{ type: 'image', data: 'AAAA', mimeType: 'image/png' }] }] }, + { role: 'system', content: 'Mid-conversation note' }, + ], { model: 'gpt-5.5' }); + assert.equal(instructions, 'Be helpful.'); + assert.equal(replayed, 1); + assert.deepEqual(input[0].content[1], { type: 'input_image', image_url: 'data:image/png;base64,QUJD', detail: 'auto' }); + assert.deepEqual(input.slice(1, 4).map(item => item.type), ['reasoning', 'function_call', 'message']); + assert.deepEqual(input[1], { type: 'reasoning', id: 'rs_1', summary: [{ type: 'summary_text', text: 'Plan' }], encrypted_content: 'enc-1' }); + assert.deepEqual(input[3], { type: 'message', role: 'assistant', content: 'Done', phase: 'final_answer' }); + assert.deepEqual(input[4].output, [{ type: 'input_text', text: 'ok' }, { type: 'input_image', image_url: 'data:image/png;base64,AAAA', detail: 'auto' }]); + assert.deepEqual(input[5], { type: 'message', role: 'developer', content: [{ type: 'input_text', text: 'Mid-conversation note' }] }); + const legacy = convertResponsesInput([{ role: 'tool', content: [{ type: 'tool-result', toolCallId: 'c', toolName: 't', result: 'ok', + experimental_content: [{ type: 'image', data: 'AAAA', mimeType: 'image/png' }] }] }], { inlineToolImages: false }); + assert.deepEqual(legacy.input.map(item => item.type), ['function_call_output', 'message']); +}); + +test('responses skips malformed historical tool calls and their results', () => { + const overLimitName = 'x'.repeat(129); + const { input } = convertResponsesInput([ + { role: 'assistant', content: [ + { type: 'tool-call', toolCallId: 'empty_call', toolName: '', args: {} }, + { type: 'tool-call', toolCallId: 'bad_call', toolName: overLimitName, args: {} }, + { type: 'tool-call', toolCallId: 'good_call', toolName: 'get_weather', args: {} }, + ] }, + { role: 'tool', content: [ + { type: 'tool-result', toolCallId: 'empty_call', toolName: '', result: 'discarded' }, + { type: 'tool-result', toolCallId: 'bad_call', toolName: overLimitName, result: 'discarded' }, + { type: 'tool-result', toolCallId: 'good_call', toolName: 'get_weather', result: 'kept' }, + ] }, + ]); + assert.deepEqual(input, [ + { type: 'function_call', call_id: 'good_call', name: 'get_weather', arguments: '{}' }, + { type: 'function_call_output', call_id: 'good_call', output: 'kept' }, + ]); +}); + +test('responses stream yields summarized reasoning, signature, text and tool calls in output order', async () => { + const { parts, response, usage, requests } = await turn('openai-responses', [() => sse([ + { type: 'response.created', response: { id: 'resp_1', model: 'gpt-5.5' } }, + { type: 'response.output_item.added', output_index: 0, item: { type: 'reasoning', id: 'rs_1' } }, + { type: 'response.reasoning_summary_text.delta', output_index: 0, summary_index: 0, delta: 'Need weather.' }, + { type: 'response.reasoning_summary_text.delta', output_index: 0, summary_index: 1, delta: 'Call tool.' }, + { type: 'response.output_item.done', output_index: 0, item: { type: 'reasoning', id: 'rs_1', summary: [{ type: 'summary_text', text: 'Need weather.' }, { type: 'summary_text', text: 'Call tool.' }], encrypted_content: 'enc' } }, + { type: 'response.output_item.added', output_index: 1, item: { type: 'message', id: 'msg_1', phase: 'commentary' } }, + { type: 'response.output_text.delta', output_index: 1, delta: 'Checking.' }, + { type: 'response.output_item.done', output_index: 1, item: { type: 'message', id: 'msg_1', phase: 'commentary', content: [{ type: 'output_text', text: 'Checking.' }] } }, + { type: 'response.output_item.added', output_index: 2, item: { type: 'function_call', id: 'fc_1', call_id: 'call_1', name: 'get_weather' } }, + { type: 'response.function_call_arguments.delta', output_index: 2, delta: '{"city":' }, + { type: 'response.function_call_arguments.delta', output_index: 2, delta: '"Paris"}' }, + { type: 'response.output_item.done', output_index: 2, item: { type: 'function_call', id: 'fc_1', call_id: 'call_1', name: 'get_weather', arguments: '{"city":"Paris"}' } }, + { type: 'response.completed', response: { id: 'resp_1', model: 'gpt-5.5', status: 'completed', + usage: { input_tokens: 20, input_tokens_details: { cached_tokens: 8 }, output_tokens: 30, output_tokens_details: { reasoning_tokens: 12 }, total_tokens: 50 } } }, + ])], { model: 'gpt-5.5', effort: 'xhigh', tools: weatherTool }); + assert.equal(requests[0].url, 'https://api.example.com/v1/responses'); + assert.equal(requests[0].headers.get('authorization'), 'Bearer k'); + assert.deepEqual(requests[0].body.reasoning, { effort: 'xhigh', summary: 'auto' }); + assert.equal(requests[0].body.store, false); + assert.deepEqual(requests[0].body.tools[0], { type: 'function', name: 'get_weather', description: 'Weather', parameters: weatherTool[0].parameters, strict: false }); + assert.deepEqual(parts.filter(part => part.type === 'reasoning').map(part => part.textDelta), ['Need weather.', '\n\nCall tool.']); + assert.equal(parts.find(part => part.type === 'reasoning').providerOptions.cursor.isAlreadySummarizedThinking, true); + assert.deepEqual(parts.find(part => part.type === 'reasoning-signature'), { type: 'reasoning-signature', signature: 'enc' }); + const content = response.messages[0].content; + assert.deepEqual(content.map(part => part.type), ['reasoning', 'text', 'tool-call']); + assert.equal(content[0].text, 'Need weather.\n\nCall tool.'); + assert.equal(content[0].providerOptions.grokbot.itemId, 'rs_1'); + assert.equal(content[1].providerOptions.grokbot.phase, 'commentary'); + assert.deepEqual(content[2].args, { city: 'Paris' }); + assert.deepEqual(usage, { promptTokens: 20, completionTokens: 30, totalTokens: 50 }); +}); + +test('responses incomplete and failed turns surface as model errors', async () => { + await assert.rejects(turn('openai-responses', [() => sse([{ type: 'response.incomplete', response: { incomplete_details: { reason: 'max_output_tokens' } } }])]), /max_output_tokens/); + await assert.rejects(turn('openai-responses', [() => sse([{ type: 'response.failed', response: { error: { code: 'context_length_exceeded', message: 'Your input exceeds the context window' } } }])]), + error => error.code === 'context_length_exceeded'); +}); + +test('responses rejects malformed model function names before persisting them', async () => { + const invalidName = 'x'.repeat(129); + await assert.rejects(turn('openai-responses', [() => sse([ + { type: 'response.output_item.added', output_index: 0, item: { type: 'function_call', call_id: 'call_1', name: invalidName } }, + { type: 'response.output_item.done', output_index: 0, item: { type: 'function_call', call_id: 'call_1', name: invalidName, arguments: '{}' } }, + { type: 'response.completed', response: { id: 'r', usage: {} } }, + ])], { tools: weatherTool }), /invalid function name/); +}); + +test('responses retries without rejected summaries and stale encrypted reasoning', async () => { + const done = () => sse([{ type: 'response.created', response: { id: 'r' } }, { type: 'response.output_text.delta', output_index: 0, delta: 'ok' }, + { type: 'response.output_item.done', output_index: 0, item: { type: 'message', content: [{ type: 'output_text', text: 'ok' }] } }, + { type: 'response.completed', response: { id: 'r', usage: { input_tokens: 1, output_tokens: 1 } } }]); + const history = [{ role: 'user', content: 'a' }, { role: 'assistant', content: [{ type: 'reasoning', text: 'x', signature: 'enc', ...responsesTag('gpt-5.5', 'rs') }, { type: 'text', text: 'b' }] }, { role: 'user', content: 'c' }]; + const { requests } = await turn('openai-responses', [ + () => failure(400, { message: 'The encrypted content for item rs could not be verified.', type: 'invalid_request_error' }), + () => failure(400, { message: "Unsupported parameter: 'reasoning.summary'", param: 'reasoning.summary', type: 'invalid_request_error' }), + done, + ], { model: 'gpt-5.5', effort: 'high', messages: history }); + assert.equal(requests[0].body.input.filter(item => item.type === 'reasoning').length, 1); + assert.equal(requests[1].body.input.filter(item => item.type === 'reasoning').length, 0); + assert.deepEqual(requests[2].body.reasoning, { effort: 'high' }); +}); + +// ---- OpenAI Chat Completions ---------------------------------------------------------- + +test('chat uses max_completion_tokens for OpenAI reasoning models and replays only its own reasoning', () => { + assert.equal(maxTokensParameter('gpt-5.5'), 'max_completion_tokens'); + assert.equal(maxTokensParameter('deepseek-v4.1-flash'), 'max_tokens'); + assert.equal(maxTokensParameter('deepseek-v4.1-flash', new Set(['max_tokens'])), 'max_completion_tokens'); + const messages = convertChatMessages([ + { role: 'user', content: 'a' }, + { role: 'assistant', content: [{ type: 'reasoning', text: 'own', ...chatTag('deepseek-v4.1-flash') }, + { type: 'reasoning', text: 'claude', signature: 's', ...anthropicTag('claude-opus-5-5') }, { type: 'text', text: 'b' }] }, + ], { model: 'deepseek-v4.1-flash' }); + assert.equal(messages[1].reasoning_content, 'own'); +}); + +test('chat skips malformed historical tool calls and their results', () => { + const overLimitName = 'x'.repeat(129); + const messages = convertChatMessages([ + { role: 'assistant', content: [ + { type: 'tool-call', toolCallId: 'empty_call', toolName: '', args: {} }, + { type: 'tool-call', toolCallId: 'bad_call', toolName: overLimitName, args: {} }, + { type: 'tool-call', toolCallId: 'good_call', toolName: 'get_weather', args: {} }, + ] }, + { role: 'tool', content: [ + { type: 'tool-result', toolCallId: 'empty_call', toolName: '', result: 'discarded' }, + { type: 'tool-result', toolCallId: 'bad_call', toolName: overLimitName, result: 'discarded' }, + { type: 'tool-result', toolCallId: 'good_call', toolName: 'get_weather', result: 'kept' }, + ] }, + ]); + assert.deepEqual(messages, [ + { role: 'assistant', content: null, tool_calls: [{ id: 'good_call', type: 'function', function: { name: 'get_weather', arguments: '{}' } }] }, + { role: 'tool', tool_call_id: 'good_call', content: 'kept' }, + ]); +}); + +test('chat stream reads reasoning_content, reasoning and refusal deltas', async () => { + const { parts, response, requests } = await turn('openai', [() => sse([ + { id: 'c1', model: 'deepseek-v4.1-flash', choices: [{ index: 0, delta: { reasoning_content: 'Think. ' } }] }, + { id: 'c1', choices: [{ index: 0, delta: { reasoning: 'More.' } }] }, + { id: 'c1', choices: [{ index: 0, delta: { content: 'Answer' } }] }, + { id: 'c1', choices: [{ index: 0, delta: { refusal: ' (partly declined)' }, finish_reason: 'stop' }] }, + { id: 'c1', choices: [], usage: { prompt_tokens: 3, completion_tokens: 4, total_tokens: 7 } }, + ], { done: true })], { model: 'deepseek-v4.1-flash', effort: 'high' }); + assert.equal(requests[0].body.reasoning_effort, 'high'); + assert.deepEqual(requests[0].body.thinking, { type: 'enabled' }); + assert.deepEqual(parts.filter(part => part.type === 'reasoning').map(part => part.textDelta), ['Think. ', 'More.']); + const content = response.messages[0].content; + assert.equal(content[0].providerOptions.grokbot.format, 'openai'); + assert.equal(content[1].text, 'Answer (partly declined)'); +}); + +test('chat rejects malformed model function names before persisting them', async () => { + const invalidName = 'x'.repeat(129); + await assert.rejects(turn('openai', [() => sse([ + { id: 'c', choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: 'call_1', function: { name: invalidName, arguments: '{}' } }] }, finish_reason: 'tool_calls' }], usage: {} }, + ], { done: true })], { tools: weatherTool }), /invalid function name/); +}); + +test('chat swaps the output limit parameter when the service rejects it', async () => { + const done = () => sse([{ id: 'c', choices: [{ index: 0, delta: { content: 'ok' }, finish_reason: 'stop' }] }], { done: true }); + const requests = []; + const session = createModelSession({ apiFormat: 'openai', baseUrl: 'https://api.example.com/v1', apiKey: 'k', model: 'gpt-5.5', + fetchImpl: async (url, options) => { requests.push(JSON.parse(options.body)); return requests.length === 1 + ? failure(400, { message: "Unsupported parameter: 'max_completion_tokens'", param: 'max_completion_tokens' }) : done(); } }); + const result = session.getExecutor([{ role: 'user', content: 'x' }]).stream({}, 'i', [], { maxTokens: 500 }); + for await (const part of result.fullStream) void part; + assert.equal(requests[0].max_completion_tokens, 500); + assert.equal(requests[1].max_tokens, 500); + assert.equal(requests[1].max_completion_tokens, undefined); +}); + +// ---- Reasoning without readable text -------------------------------------------------- + +test('signed thinking without text is kept as a redacted part and replayed as thinking', async () => { + const { parts, response } = await turn('anthropic', [() => sse([ + { type: 'message_start', message: { id: 'm', model: 'claude-opus-5-5', usage: {} } }, + { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '', signature: '' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: 'sig-empty' } }, + { type: 'content_block_stop', index: 0 }, + { type: 'content_block_start', index: 1, content_block: { type: 'text', text: 'ok' } }, + { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 1 } }, { type: 'message_stop' }, + ])], { model: 'claude-opus-5-5' }); + assert.equal(parts.filter(part => part.type === 'reasoning').length, 0); + const redacted = response.messages[0].content[0]; + assert.equal(redacted.type, 'redacted-reasoning'); + assert.equal(redacted.data, 'sig-empty'); + const { messages } = convertAnthropicMessages([{ role: 'user', content: 'a' }, { role: 'assistant', content: [redacted, { type: 'text', text: 'ok' }] }, { role: 'user', content: 'b' }]); + assert.deepEqual(messages[1].content[0], { type: 'thinking', thinking: '', signature: 'sig-empty' }); +}); + +test('encrypted reasoning without a summary is kept as a redacted part and replayed', async () => { + const { parts, response } = await turn('openai-responses', [() => sse([ + { type: 'response.created', response: { id: 'r', model: 'gpt-5.5' } }, + { type: 'response.output_item.added', output_index: 0, item: { type: 'reasoning', id: 'rs_9' } }, + { type: 'response.output_item.done', output_index: 0, item: { type: 'reasoning', id: 'rs_9', summary: [], encrypted_content: 'enc-9' } }, + { type: 'response.output_text.delta', output_index: 1, delta: 'ok' }, + { type: 'response.output_item.done', output_index: 1, item: { type: 'message', content: [{ type: 'output_text', text: 'ok' }] } }, + { type: 'response.completed', response: { id: 'r', usage: { input_tokens: 1, output_tokens: 1 } } }, + ])], { model: 'gpt-5.5', effort: 'high' }); + assert.equal(parts.find(part => part.type === 'redacted-reasoning').data, 'enc-9'); + const redacted = response.messages[0].content[0]; + assert.equal(redacted.type, 'redacted-reasoning'); + const { input } = convertResponsesInput([{ role: 'user', content: 'a' }, { role: 'assistant', content: [redacted, { type: 'text', text: 'ok' }] }], { model: 'gpt-5.5' }); + assert.deepEqual(input[1], { type: 'reasoning', id: 'rs_9', summary: [], encrypted_content: 'enc-9' }); +}); diff --git a/host/tests/model-redirect.test.mjs b/host/tests/model-redirect.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bb00d0559e6ae503f66d3705f4d8d35120204e58 --- /dev/null +++ b/host/tests/model-redirect.test.mjs @@ -0,0 +1,19 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import test from 'node:test'; +import { postWithFallback } from '../runtime/model-common.mjs'; + +test('model requests never forward credentials or conversation bodies through a redirect', async t => { + async function listen(handler) { + const server = createServer(handler); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); }); + return `http://127.0.0.1:${server.address().port}`; + } + let hits = 0; + const other = await listen((_req, res) => { hits++; res.end('unexpected'); }); + const url = await listen((_req, res) => { res.writeHead(307, { location: other }); res.end(); }); + await assert.rejects(postWithFallback({ fetchImpl: fetch, url, headers: { 'x-api-key': 'test-only' }, + build: () => ({ messages: ['private'] }), state: { dropped: new Set() } })); + assert.equal(hits, 0); +}); diff --git a/host/tests/model-rejection-guard.test.mjs b/host/tests/model-rejection-guard.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0621fd7f0b363e4b3bb1de913d88cb4badf0b713 --- /dev/null +++ b/host/tests/model-rejection-guard.test.mjs @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { installModelRejectionGuard, isContainedModelRejection } from '../runtime/model-rejection-guard.mjs'; + +test('contains only rejections caused by the local model adapter', () => { + const upstream = Object.assign(new Error('API key quota exhausted'), { + name: 'ModelRequestError', status: 429, code: 'API_KEY_QUOTA_EXHAUSTED', + }); + const harness = Object.assign(new Error('request failed'), { name: 'NonRetriableError', cause: upstream }); + assert.equal(isContainedModelRejection(harness), true); + assert.equal(isContainedModelRejection(upstream), true); + assert.equal(isContainedModelRejection(new Error('unrelated defect')), false); + assert.equal(isContainedModelRejection({ cause: { name: 'TypeError' } }), false); +}); + +test('the process guard contains a model failure but preserves unrelated rejection failure', () => { + let listener; + installModelRejectionGuard({ on(event, callback) { assert.equal(event, 'unhandledRejection'); listener = callback; } }); + const original = console.error, messages = []; + console.error = message => messages.push(message); + try { + listener(Object.assign(new Error('quota'), { cause: Object.assign(new Error('provider'), { name: 'ModelRequestError', status: 429 }) })); + } finally { + console.error = original; + } + assert.match(messages[0], /contained unhandled model rejection/); + assert.throws(() => listener(new Error('unrelated defect')), /unrelated defect/); +}); diff --git a/host/tests/model-routing.test.mjs b/host/tests/model-routing.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a88abf18b9c1b0224afa21276c3457baaaa65fcb --- /dev/null +++ b/host/tests/model-routing.test.mjs @@ -0,0 +1,364 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createModelSession } from '../runtime/model-session.mjs'; +import { convertAnthropicMessages } from '../runtime/anthropic-messages.mjs'; +import { convertChatMessages } from '../runtime/openai-chat.mjs'; +import { readSse, reasoningProviderOptions } from '../runtime/model-common.mjs'; +import { loadModelConfig } from '../runtime/config.mjs'; +import { contextPolicyFor } from '../runtime/context-policy.mjs'; +import { installHostNetworkBoundary } from '../runtime/host-network.mjs'; +import { createInference } from '../runtime/host-extensions.mjs'; +import { catalogContextPolicy, defaultPolicy } from '../runtime/model-policy.mjs'; +import { legacyModelRouting, modelRouteForAgent, parseModelRouting, publicModelRouting, validateModelRouting } from '../runtime/model-routing.mjs'; +import { Models } from '../server/models.mjs'; + +const primary = { profileId: 'fast', providerId: 'primary', providerName: 'Primary', apiFormat: 'openai', + baseUrl: 'https://primary.example/v1', apiKey: 'test-primary-key', model: 'gpt-fast', efforts: ['none', 'low'], effort: 'low', + contextWindowTokens: 64_000, summaryThresholdTokens: 48_000 }; +const fallback = { profileId: 'careful', providerId: 'backup', providerName: 'Backup', apiFormat: 'openai', + baseUrl: 'https://backup.example/v1', apiKey: 'test-backup-key', model: 'gpt-careful', efforts: ['medium', 'high'], effort: 'high', + contextWindowTokens: 32_000, summaryThresholdTokens: 24_000 }; + +const fixture = () => ({ + version: 1, + providers: [ + { id: 'primary', name: 'Primary', apiFormat: 'openai', baseUrl: primary.baseUrl, apiKey: primary.apiKey }, + { id: 'backup', name: 'Backup', apiFormat: 'openai-responses', baseUrl: fallback.baseUrl, apiKey: fallback.apiKey }, + ], + profiles: [ + { id: 'fast', name: 'Fast', providerId: 'primary', model: 'gpt-fast', efforts: ['none', 'low'], contextWindowTokens: 64_000, summaryThresholdTokens: 48_000 }, + { id: 'careful', name: 'Careful', providerId: 'backup', model: 'gpt-careful', efforts: ['medium', 'high'], contextWindowTokens: 32_000, summaryThresholdTokens: 24_000 }, + ], + defaultRoute: { profileId: 'fast', effort: 'low', fallbacks: [{ profileId: 'careful', effort: 'high' }] }, + botRoutes: { bot_alpha: { profileId: 'careful', effort: 'medium', fallbacks: [{ profileId: 'fast', effort: 'none' }] } }, +}); + +const sse = text => new Response(`data: ${JSON.stringify({ id: 'chat_1', model: 'gpt-careful', choices: [{ index: 0, delta: { content: text }, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`, { + status: 200, headers: { 'content-type': 'text/event-stream' }, +}); +const responsesSse = text => new Response([ + { type: 'response.output_text.delta', output_index: 0, item_id: 'msg_1', delta: text }, + { type: 'response.output_item.done', output_index: 0, item: { type: 'message', id: 'msg_1', + status: 'completed', content: [{ type: 'output_text', text }] } }, + { type: 'response.completed', response: { id: 'resp_1', model: 'gpt-careful', status: 'completed', + output: [{ type: 'message', id: 'msg_1', status: 'completed', content: [{ type: 'output_text', text }] }] } }, +].map(event => `data: ${JSON.stringify(event)}\n\n`).join(''), { + status: 200, headers: { 'content-type': 'text/event-stream' }, +}); +const failure = status => new Response(JSON.stringify({ error: { message: `HTTP ${status}` } }), { status, + headers: { 'content-type': 'application/json' } }); + +async function streamWithFallback(replies, { candidates = [primary, fallback], signal, messages = [{ role: 'user', content: 'Hello' }] } = {}) { + const requests = [], fallbacks = []; + const session = createModelSession({ ...primary, fetchImpl: async (url, options) => { + requests.push({ url, body: JSON.parse(options.body) }); + const reply = replies.shift(); + return typeof reply === 'function' ? reply() : reply; + }, selectRequest: async () => ({ ...candidates[0], fallbacks: candidates.slice(1) }), + onFallback: event => fallbacks.push(event) }); + const result = session.getExecutor(messages).stream({ signal }, 'routing-test', []); + const parts = []; + for await (const part of result.fullStream) parts.push(part); + return { parts, requests, fallbacks, response: await result.response }; +} + +test('routes choose per-Bot providers, efforts and ordered backups without exposing keys', () => { + const config = validateModelRouting(fixture()); + const defaultRoute = modelRouteForAgent(config); + const botRoute = modelRouteForAgent(config, 'bot_alpha'); + assert.deepEqual([defaultRoute.providerId, defaultRoute.model, defaultRoute.effort], ['primary', 'gpt-fast', 'low']); + assert.deepEqual(defaultRoute.fallbacks.map(item => [item.providerId, item.model, item.effort]), [['backup', 'gpt-careful', 'high']]); + assert.equal(defaultRoute.contextWindowTokens, 32_000); + assert.deepEqual([botRoute.providerId, botRoute.model, botRoute.effort], ['backup', 'gpt-careful', 'medium']); + assert.deepEqual(botRoute.fallbacks.map(item => [item.providerId, item.model, item.effort]), [['primary', 'gpt-fast', 'none']]); + const publicConfig = publicModelRouting(config); + assert.equal(JSON.stringify(publicConfig).includes('test-primary-key'), false); + assert.equal(publicConfig.providers[0].hasApiKey, true); +}); + +test('Host inference selects a Bot route at the real HTTP request boundary', async t => { + const directory = await mkdtemp(join(tmpdir(), 'host-inference-routing-')); + t.after(() => rm(directory, { recursive: true, force: true })); + const routing = validateModelRouting(fixture()); + const config = { + ...primary, + modelRouting: routing, + policy: defaultPolicy(primary.model), + usageDirectory: join(directory, 'usage'), + routingDirectory: join(directory, 'routing'), + modelBaseUrls: routing.providers.map(provider => provider.baseUrl), + }; + const requests = []; + class HarnessError extends Error {} + const library = { + PrivacyMode: { NO_STORAGE: 'no-storage' }, + ConnectError: HarnessError, + ActionRequiredError: HarnessError, + NonRetriableError: HarnessError, + Code: { ResourceExhausted: 8, Unavailable: 14, Internal: 13 }, + }; + const inference = createInference(config, library, {}, { + fetchImpl: async (url, options) => { + requests.push({ url, body: JSON.parse(options.body) }); + return JSON.parse(options.body).model === 'gpt-careful' ? responsesSse('OK') : sse('OK'); + }, + }); + + const run = async options => { + const session = inference.port.createSession(() => {}, options); + const result = session.getExecutor([{ role: 'user', content: 'Hello' }]).stream({}, 'routing-entry', []); + await Array.fromAsync(result.fullStream); + await result.response; + }; + await run({ agentId: 'bot_alpha' }); + await run({ getAgentId: () => 'bot_alpha' }); + await run({}); + + assert.deepEqual(requests.map(request => [request.url, request.body.model, + request.body.reasoning_effort ?? request.body.reasoning?.effort]), [ + ['https://backup.example/v1/responses', 'gpt-careful', 'medium'], + ['https://backup.example/v1/responses', 'gpt-careful', 'medium'], + ['https://primary.example/v1/chat/completions', 'gpt-fast', 'low'], + ]); +}); + +test('legacy single-provider configuration remains editable as a direct default route', () => { + const legacy = { apiFormat: 'openai', baseUrl: 'https://legacy.example/v1', apiKey: 'test-legacy-key', model: 'legacy-model', + contextWindowTokens: 16_000, policy: { effort: 'high', models: [{ id: 'legacy-model', efforts: ['low', 'high'] }] } }; + const { config, migrated } = parseModelRouting(undefined, legacy); + assert.equal(migrated, true); + assert.deepEqual(modelRouteForAgent(config).model, 'legacy-model'); + assert.equal(legacyModelRouting({}).providers.length, 0); +}); + +test('catalog context policies use provider metadata and never assume capacity for an unknown model', () => { + assert.deepEqual(catalogContextPolicy('provider-model', 128_000), { + contextWindowTokens: 128_000, summaryThresholdTokens: 96_000, contextSource: 'provider', + }); + assert.deepEqual(catalogContextPolicy('gpt-5.6-terra'), { + contextWindowTokens: 0, summaryThresholdTokens: 0, contextSource: 'unknown', + }); + assert.deepEqual(catalogContextPolicy('unpublished-model'), { + contextWindowTokens: 0, summaryThresholdTokens: 0, contextSource: 'unknown', + }); +}); + +test('new profiles do not assume a compaction policy without provider metadata', () => { + const input = fixture(); + input.profiles = [{ id: 'new', name: 'New', providerId: 'primary', model: 'new-model', efforts: [] }, + { id: 'disabled', name: 'Disabled', providerId: 'primary', model: 'disabled-model', efforts: [], + contextWindowTokens: 0, summaryThresholdTokens: 0 }]; + input.defaultRoute = { profileId: 'new', effort: 'default', fallbacks: [] }; + input.botRoutes = {}; + const profiles = new Map(validateModelRouting(input).profiles.map(profile => [profile.id, profile])); + assert.deepEqual(profiles.get('new').contextWindowTokens, 0); + assert.deepEqual(profiles.get('new').summaryThresholdTokens, 0); + assert.deepEqual(profiles.get('disabled').contextWindowTokens, 0); + assert.deepEqual(profiles.get('disabled').summaryThresholdTokens, 0); +}); + +test('SSE parser accepts adjacent data frames from compatible gateways', async () => { + const first = JSON.stringify({ choices: [{ delta: { role: 'assistant' } }] }); + const second = JSON.stringify({ choices: [{ delta: { content: 'OK' }, finish_reason: 'stop' }] }); + const wire = `data: ${first}data: ${second}data: [DONE]`; + const encoder = new TextEncoder(); + const body = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(wire.slice(0, 17))); + controller.enqueue(encoder.encode(wire.slice(17, 71))); + controller.enqueue(encoder.encode(wire.slice(71))); + controller.close(); + }, + }); + const events = []; + for await (const event of readSse(body)) events.push(event); + assert.deepEqual(events, [first, second, '[DONE]']); +}); + +test('loadModelConfig retains every provider base URL for the Host network boundary', async t => { + const directory = await mkdtemp(join(tmpdir(), 'model-routing-')); + t.after(() => rm(directory, { recursive: true, force: true })); + await writeFile(join(directory, 'model.env'), `GROKBOT_MODEL_ROUTING=${JSON.stringify(fixture())}\n`); + const config = await loadModelConfig({ env: { GROKBOT_MODEL_ENV: join(directory, 'model.env'), GROKBOT_DATA_DIR: directory } }); + assert.deepEqual(config.modelBaseUrls, ['https://primary.example/v1', 'https://backup.example/v1']); +}); + +test('model administration keeps saved provider keys private and preserves them on an unchanged provider', async t => { + const directory = await mkdtemp(join(tmpdir(), 'model-routing-admin-')); + t.after(() => rm(directory, { recursive: true, force: true })); + const models = new Models(directory); + await models.save({ ...fixture(), migrateLegacyRouting: true }); + const publicConfig = await models.publicConfig(); + assert.equal(JSON.stringify(publicConfig).includes('test-primary-key'), false); + assert.equal(JSON.stringify(publicConfig).includes('test-backup-key'), false); + const unchanged = fixture(); + unchanged.providers = unchanged.providers.map(({ apiKey, ...provider }) => provider); + await models.save(unchanged); + const current = await models.current(); + assert.equal(current.routing.providers.find(provider => provider.id === 'primary').apiKey, 'test-primary-key'); + assert.equal(current.routing.providers.find(provider => provider.id === 'backup').apiKey, 'test-backup-key'); +}); + +test('legacy Jev configuration remains in the legacy format until an administrator migrates it', async t => { + const directory = await mkdtemp(join(tmpdir(), 'model-routing-legacy-')); + t.after(() => rm(directory, { recursive: true, force: true })); + const policy = defaultPolicy('legacy-model'); + policy.mode = 'adaptive'; + const models = new Models(directory); + await models.save({ apiFormat: 'openai', baseUrl: 'https://legacy.example/v1', apiKey: 'test-legacy-key', model: 'legacy-model', + contextWindowTokens: 16_000, policy, jevApiKey: 'test-jev-key' }); + const source = await readFile(join(directory, 'model.env'), 'utf8'); + assert.doesNotMatch(source, /^GROKBOT_MODEL_ROUTING=/m); + const loaded = await loadModelConfig({ env: { GROKBOT_MODEL_ENV: join(directory, 'model.env'), GROKBOT_DATA_DIR: directory } }); + assert.equal(loaded.policy.mode, 'adaptive'); + assert.equal(loaded.jevApiKey, 'test-jev-key'); + assert.equal((await models.publicConfig()).legacyAdaptiveRouting, true); + await assert.rejects(models.save(fixture()), { status: 409, message: /旧版模型配置/ }); + assert.equal(await readFile(join(directory, 'model.env'), 'utf8'), source); + const migrated = await models.save({ ...fixture(), migrateLegacyRouting: true }); + assert.equal(migrated.routingMigrated, false); + assert.equal(migrated.legacyAdaptiveRouting, false); + assert.match(await readFile(join(directory, 'model.env'), 'utf8'), /^GROKBOT_MODEL_ROUTING=/m); +}); + +test('a legacy single-model configuration is not reported as task-difficulty routing', async t => { + const directory = await mkdtemp(join(tmpdir(), 'model-routing-legacy-single-')); + t.after(() => rm(directory, { recursive: true, force: true })); + const models = new Models(directory); + await models.save({ apiFormat: 'openai', baseUrl: 'https://legacy.example/v1', apiKey: 'test-legacy-key', model: 'legacy-model', + contextWindowTokens: 16_000, policy: defaultPolicy('legacy-model') }); + const publicConfig = await models.publicConfig(); + assert.equal(publicConfig.routingMigrated, true); + assert.equal(publicConfig.legacyAdaptiveRouting, false); +}); + +test('transient failures before output move to the next configured model', async () => { + for (const retryable of [() => failure(503), () => failure(429), () => { throw new TypeError('socket closed'); }, + () => { const error = new DOMException('timed out', 'TimeoutError'); throw error; }]) { + const { requests, fallbacks, response } = await streamWithFallback([retryable, sse('OK')]); + assert.equal(requests.length, 2); + assert.equal(requests[0].url, 'https://primary.example/v1/chat/completions'); + assert.equal(requests[1].url, 'https://backup.example/v1/chat/completions'); + assert.equal(fallbacks.length, 1); + assert.equal(fallbacks[0].from.profileId, 'fast'); + assert.equal(fallbacks[0].to.profileId, 'careful'); + assert.equal(response.modelId, 'gpt-careful'); + } +}); + +test('configuration errors and cancellation do not start a backup model', async () => { + await assert.rejects(streamWithFallback([() => failure(400), sse('unexpected')]), /HTTP 400/); + const cancellation = new AbortController(); + cancellation.abort(new DOMException('Canceled', 'AbortError')); + await assert.rejects(streamWithFallback([sse('unexpected')], { signal: cancellation.signal }), /Canceled/); +}); + +test('a model that has emitted visible text is never retried on another provider', async () => { + const encoder = new TextEncoder(); + const broken = () => { + let sent = false; + return new Response(new ReadableStream({ + pull(controller) { + if (!sent) { + sent = true; + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: 'partial answer' } }] })}\n\n`)); + return; + } + controller.error(new TypeError('connection reset')); + }, + }), { status: 200, headers: { 'content-type': 'text/event-stream' } }); + }; + const requests = [], events = []; + const session = createModelSession({ ...primary, fetchImpl: async (url, options) => { requests.push({ url, options }); return broken(); }, + selectRequest: async () => ({ ...primary, fallbacks: [fallback] }), onFallback: event => events.push(event) }); + const result = session.getExecutor([{ role: 'user', content: 'Hello' }]).stream({}, 'no-retry-after-output', []); + const parts = []; + await assert.rejects(async () => { for await (const part of result.fullStream) parts.push(part); }, /connection reset/); + assert.equal(requests.length, 1); + assert.equal(events.length, 0); + assert.equal(parts.length, 1); +}); + +test('a model that has emitted only reasoning may use its configured backup', async () => { + const encoder = new TextEncoder(); + const broken = () => { + let sent = false; + return new Response(new ReadableStream({ + pull(controller) { + if (!sent) { + sent = true; + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { reasoning_content: 'partial reasoning' } }] })}\n\n`)); + return; + } + controller.error(new TypeError('connection reset')); + }, + }), { status: 200, headers: { 'content-type': 'text/event-stream' } }); + }; + const { requests, fallbacks, response } = await streamWithFallback([broken, sse('OK')]); + assert.equal(requests.length, 2); + assert.equal(fallbacks.length, 1); + assert.equal(response.modelId, 'gpt-careful'); +}); + +test('legacy model.env context and summary thresholds enable compaction through the real config path', async t => { + const directory = await mkdtemp(join(tmpdir(), 'model-routing-compaction-')); + t.after(() => rm(directory, { recursive: true, force: true })); + const policy = defaultPolicy('legacy-compaction-model'); + policy.models = [{ id: 'legacy-compaction-model', efforts: ['low'], + contextWindowTokens: 128_000, summaryThresholdTokens: 96_000 }]; + await writeFile(join(directory, 'model.env'), [ + 'MODEL_API_FORMAT=openai', + 'OPENAI_BASE_URL=https://legacy.example/v1', + 'OPENAI_API_KEY=test-legacy-key', + 'OPENAI_MODEL=legacy-compaction-model', + 'OPENAI_CONTEXT_WINDOW_TOKENS=128000', + `GROKBOT_MODEL_POLICY=${JSON.stringify(policy)}`, + '', + ].join('\n')); + const config = await loadModelConfig({ env: { GROKBOT_MODEL_ENV: join(directory, 'model.env'), GROKBOT_DATA_DIR: directory } }); + const context = contextPolicyFor(config, config.model); + assert.deepEqual(context, { contextWindowTokens: 128_000, summaryThresholdTokens: 96_000 }); + const session = createModelSession({ ...config, ...context, fetchImpl: async () => sse('OK'), + selectRequest: async () => ({ model: config.model, ...context, fallbacks: [] }) }); + const result = session.getExecutor([{ role: 'user', content: 'Hello' }]).stream({}, 'legacy-compaction', []); + await Array.fromAsync(result.fullStream); + const response = await result.response; + assert.equal(response.supportsSelfSummary, true); + assert.equal(response.earlyCompactionContextTokenThreshold, 96_000); +}); + +test('configured summary thresholds are advertised to the Harness after a successful model response', async () => { + const session = createModelSession({ ...primary, contextWindowTokens: 258_000, summaryThresholdTokens: 192_000, + fetchImpl: async () => sse('OK'), selectRequest: async () => ({ ...primary, + contextWindowTokens: 258_000, summaryThresholdTokens: 192_000, fallbacks: [] }) }); + const result = session.getExecutor([{ role: 'user', content: 'Hello' }]).stream({}, 'compaction-capability', []); + for await (const _part of result.fullStream) { /* consume the response */ } + const response = await result.response; + assert.equal(response.supportsSelfSummary, true); + assert.equal(response.earlyCompactionContextTokenThreshold, 192_000); + assert.deepEqual(session.getEarlyCompaction(), { threshold: 192_000, inputTokens: 0 }); +}); + +test('reasoning replay is isolated by provider and API format, not by a provider-rewritten model ID', () => { + const history = [{ role: 'user', content: 'Start' }, { role: 'assistant', content: [{ type: 'reasoning', text: 'Private chain', + ...{ providerOptions: reasoningProviderOptions({ format: 'openai', model: 'same-model', providerId: 'one' }) } }] }]; + assert.equal(convertChatMessages(history, { model: 'same-model', providerId: 'one' })[1].reasoning_content, 'Private chain'); + assert.equal(convertChatMessages(history, { model: 'same-model', providerId: 'two' })[1].reasoning_content, undefined); + const anthropicHistory = [{ role: 'user', content: 'Start' }, { role: 'assistant', content: [{ type: 'reasoning', text: 'Signed chain', signature: 'sig', + ...{ providerOptions: reasoningProviderOptions({ format: 'anthropic', model: 'claude-one', providerId: 'one' }) } }, { type: 'text', text: 'Done' }] }]; + assert.equal(convertAnthropicMessages(anthropicHistory, { model: 'claude-one', providerId: 'one' }).messages[1].content[0].type, 'thinking'); + assert.equal(convertAnthropicMessages(anthropicHistory, { model: 'claude-one-2026-01-01', providerId: 'one' }).messages[1].content[0].type, 'thinking'); + assert.equal(convertAnthropicMessages(anthropicHistory, { model: 'claude-one', providerId: 'two' }).messages[1].content[0].type, 'text'); +}); + +test('the Host network boundary accepts every configured model provider', async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => new Response('ok'); + installHostNetworkBoundary(['https://primary.example/v1', 'https://backup.example/v1']); + assert.equal((await globalThis.fetch('https://backup.example/v1/models')).status, 200); + await assert.rejects(globalThis.fetch('https://blocked.example/v1/models'), /Host network capability unavailable/); + void originalFetch; +}); diff --git a/host/tests/model-stream-regression.test.mjs b/host/tests/model-stream-regression.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ae5b026eccc5786f16a0007208617d482f7d4233 --- /dev/null +++ b/host/tests/model-stream-regression.test.mjs @@ -0,0 +1,522 @@ +import assert from 'node:assert/strict'; +import { getEventListeners } from 'node:events'; +import { createServer } from 'node:http'; +import test from 'node:test'; +import { setImmediate as tick, setTimeout as delay } from 'node:timers/promises'; +import { errorFromResponse, readSse } from '../runtime/model-common.mjs'; +import { createHarnessModelErrorMapper } from '../runtime/model-errors.mjs'; +import { awaitToolCallTurn } from '../runtime/reliability/tool-order.mjs'; +import { API_FORMATS, createModelSession } from '../runtime/model-session.mjs'; + +const history = [{ role: 'user', content: 'Synthetic stream check.' }]; +const tools = [{ name: 'record', parameters: { type: 'object', properties: { value: { type: 'integer' } } } }]; +const slots = ['response', 'usage', 'extendedUsage', 'providerMetadata', 'invocationId']; +const frame = value => `data: ${typeof value === 'string' ? value : JSON.stringify(value)}\n\n`; +const frames = events => events.map(frame).join(''); +const choice = (delta, finish_reason = null) => ({ choices: [{ index: 0, delta, finish_reason }] }); +const completed = response => ({ type: 'response.completed', response: { status: 'completed', ...response } }); +const functionItem = (id, index) => ({ type: 'function_call', id: `item_${index}`, call_id: id, + name: 'record', arguments: JSON.stringify({ value: index }) }); + +function toolEvents(format, ids = ['one']) { + if (format === 'openai') return ids.map((id, index) => choice({ tool_calls: [ + { index, id, function: { name: 'record', arguments: JSON.stringify({ value: index }) } }] })); + if (format === 'openai-responses') return ids.map((id, index) => ({ type: 'response.output_item.done', + output_index: index, item: functionItem(id, index) })); + return [{ type: 'message_start', message: { id: 'msg', usage: { input_tokens: 2 } } }, + ...ids.flatMap((id, index) => [ + { type: 'content_block_start', index, content_block: { type: 'tool_use', id, name: 'record', input: {} } }, + { type: 'content_block_delta', index, delta: { type: 'input_json_delta', partial_json: JSON.stringify({ value: index }) } }, + { type: 'content_block_stop', index }, + ])]; +} + +function ending(format) { + if (format === 'openai') return [choice({}, 'tool_calls'), + { choices: [], usage: { prompt_tokens: 2, completion_tokens: 3 } }, '[DONE]']; + if (format === 'openai-responses') return [completed({ usage: { input_tokens: 2, output_tokens: 3 } })]; + return [{ type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 3 } }, + { type: 'message_stop' }]; +} + +function messageEvents(format, id, args) { + const name = 'SendToUser', json = JSON.stringify(args); + if (format === 'openai') return [choice({ tool_calls: [{ index: 0, id, function: { name, arguments: json } }] })]; + if (format === 'openai-responses') return [{ type: 'response.output_item.done', output_index: 0, + item: { type: 'function_call', id: `item_${id}`, call_id: id, name, arguments: json } }]; + return [{ type: 'message_start', message: { id: `msg_${id}`, usage: { input_tokens: 2 } } }, + { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', name, id, input: {} } }, + { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: json } }, + { type: 'content_block_stop', index: 0 }]; +} + +function sentHistory(args) { + const toolName = 'SendToUser', toolCallId = 'first-reply'; + return [...history, { role: 'assistant', id: 'response-first', content: [{ type: 'tool-call', toolName, toolCallId, args }] }, + { role: 'tool', id: toolCallId, content: [{ type: 'tool-result', toolName, toolCallId, result: 'Message sent.' }], + providerOptions: { cursor: { highLevelToolCallResult: { isError: false } } } }]; +} + +async function loopback(t, reply) { + const requests = []; + const server = createServer(async (req, res) => { + let text = ''; + for await (const chunk of req) text += chunk; + requests.push({ path: req.url, body: JSON.parse(text) }); + reply(res, requests.length); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); }); + return { baseUrl: `http://127.0.0.1:${server.address().port}/v1`, requests }; +} + +function stream(apiFormat, baseUrl, config, signal) { + return createModelSession({ model: 'fixture', apiFormat, baseUrl, ...config }) + .getExecutor(history).stream({ signal }, 'fixture-turn', tools); +} + +async function rejectedSlots(result, reason) { + for (const key of slots) await assert.rejects(result[key], error => error === reason, key); +} + +async function rejectedTurn(result, expected) { + const emitted = []; + let reason; + try { for await (const part of result.fullStream) emitted.push(part.type); } catch (error) { reason = error; } + assert.ok(reason, `Unexpected success: ${emitted.join(', ')}`); + if (expected instanceof RegExp) assert.match(reason.message, expected); + else expected(reason); + assert.ok(!emitted.some(type => type === 'finish' || type.startsWith('tool-call')), `Leaked: ${emitted.join(', ')}`); + await rejectedSlots(result, reason); +} + +test('oversized provider error bodies stop reading and retain HTTP retry information', async () => { + const chunk = new Uint8Array(8192).fill(32); + for (const headers of [{}, { 'content-length': '1' }]) { + let pulled = 0, cancelled = false; + const body = new ReadableStream({ + pull(c) { if (++pulled <= 12) c.enqueue(chunk); else c.close(); }, + cancel() { cancelled = true; }, + }, { highWaterMark: 0 }); + const e = await errorFromResponse(new Response(body, { status: 429, headers: { ...headers, 'retry-after': '2' } })); + assert.equal(e.status, 429); assert.equal(e.retryAfterMs, 2000); + assert.ok(pulled <= 9 && cancelled && !body.locked, `pulled ${pulled}, cancelled ${cancelled}`); + assert.match(e.message, /429.*64 KiB/); assert.equal(e.code, undefined); + } +}); + +test('provider error body exactly at the limit preserves code, parameter and redaction', async () => { + const credential = 'synthetic-private-token'; + const text = JSON.stringify({ error: { message: `Unknown field. ${credential}`, param: 'effort', code: 'invalid_request_error' } }); + const bytes = Buffer.from(text.padEnd(64 * 1024)); + const body = new ReadableStream({ start(c) { c.enqueue(bytes.subarray(0, 31)); c.enqueue(bytes.subarray(31)); c.close(); } }); + const e = await errorFromResponse(new Response(body, { status: 400 }), credential); + assert.equal(e.code, 'invalid_request_error'); assert.equal(e.param, 'effort'); + assert.equal(e.message, 'Unknown field. [redacted]'); assert.equal(body.locked, false); +}); + +test('provider error body read failures preserve transport errors; empty and non-JSON keep HTTP status', async () => { + for (const data of [null, '', 'bad gateway']) { + const e = await errorFromResponse(new Response(data, { status: 502 })); + assert.equal(e.message, 'Model request failed (HTTP 502)'); + } + const cause = new Error('reply interrupted'); + const body = new ReadableStream({ start(c) { c.error(cause); } }); + await assert.rejects(errorFromResponse(new Response(body, { status: 502 })), error => error === cause); + assert.equal(body.locked, false); +}); + +for (const format of API_FORMATS) { + test(`${format}: an autonomous repeated plain-text delivery fails visibly before any tool handoff`, async t => { + const args = { type: 'text', content: 'Synthetic reply.' }, id = `${format}-resend`, usage = []; + const { baseUrl, requests } = await loopback(t, res => res.end(frames([...messageEvents(format, id, + { content: args.content, type: args.type }), ...ending(format)]))); + class NonRetriableError extends Error { constructor(msg, options) { super(msg, options); this.displayInfo = options.displayInfo; } } + const mapError = createHarnessModelErrorMapper({ Code: { ResourceExhausted: 8, Unavailable: 14, Internal: 13 }, + NonRetriableError, ConnectError: Error, ActionRequiredError: Error }); + const result = createModelSession({ model: 'fixture', apiFormat: format, baseUrl, mapError, onUsage: u => usage.push(u) }) + .getExecutor(sentHistory(args)).stream({}, 'next-step', []); + await rejectedTurn(result, e => { + assert.ok(e instanceof NonRetriableError); assert.equal(e.cause.code, 'repeated_user_delivery'); + assert.equal(e.displayInfo.isRetryable, false); assert.match(e.message, /already delivered/i); + assert.ok(!e.message.includes(args.content)); + }); + assert.equal(requests.length, 1); assert.equal(usage.length, 1, 'the upstream generation was billed'); + const body = JSON.stringify(requests[0].body); assert.ok(body.includes('first-reply') && body.includes('Message sent.')); + }); + + test(`${format}: new user turns, different text and unsuccessful deliveries are not suppressed`, async () => { + const args = { type: 'text', content: 'Same answer.' }; + const examples = [ + msgs => msgs.push({ role: 'user', content: 'Please repeat that.' }), + msgs => { msgs[1].content[0].args = { ...args, content: 'A different answer.' }; }, + msgs => { msgs[2].providerOptions.cursor.highLevelToolCallResult.isError = true; }, + msgs => { delete msgs[2].providerOptions; }, + msgs => { msgs[2].content[0].toolCallId = 'unrelated-result'; }, + msgs => { msgs[1].content[0].args = { ...args, attachment: 'different' }; }, + ]; + for (const [i, edit] of examples.entries()) { + const msgs = sentHistory(args); edit(msgs); const id = `${format}-allowed-${i}`; + const fetchImpl = async () => new Response(frames([...messageEvents(format, id, args), ...ending(format)])); + const result = createModelSession({ model: 'fixture', apiFormat: format, baseUrl: 'http://127.0.0.1', fetchImpl }) + .getExecutor(msgs).stream({}, 'next-step', []); + try { assert.deepEqual((await Array.fromAsync(result.fullStream)).filter(p => p.type === 'tool-call').map(p => p.toolCallId), [id]); } + finally { (await awaitToolCallTurn(id))(); } + } + }); + + test(`${format}: EOF before the terminal event does not publish a tool or retry`, async t => { + // Chat accepts either [DONE] or a finish reason, so its truncated stream carries neither. + const cut = format === 'openai' ? ending(format).slice(1, -1) : ending(format).slice(0, -1); + const { baseUrl, requests } = await loopback(t, res => res.end(frames([...toolEvents(format), ...cut]))); + await rejectedTurn(stream(format, baseUrl), /completion marker/i); + assert.equal(requests.length, 1); + }); + + test(`${format}: EOF in the final SSE frame cannot certify the turn`, async t => { + const [finish, usage] = ending(format); + const last = format === 'openai' ? [usage, finish] : ending(format); + const wire = frames([...toolEvents(format), ...last]).slice(0, -1); + const { baseUrl } = await loopback(t, res => res.end(wire)); + await rejectedTurn(stream(format, baseUrl), /completion marker/i); + }); + + test(`${format}: duplicate IDs reject the whole tool batch before handoff`, async t => { + const wire = frames([...toolEvents(format, ['same', 'same']), ...ending(format)]); + const { baseUrl, requests } = await loopback(t, res => res.end(wire)); + await rejectedTurn(stream(format, baseUrl), /duplicate.*tool/i); + assert.equal(requests.length, 1); + }); + + test(`${format}: valid parallel tools are handed off once in output order`, async t => { + const wire = frames([...toolEvents(format, ['first', 'second']), ...ending(format)]); + const { baseUrl, requests } = await loopback(t, res => res.end(wire)); + const result = stream(format, baseUrl), parts = await Array.fromAsync(result.fullStream); + const calls = parts.filter(part => part.type === 'tool-call'); + assert.deepEqual(calls.map(part => [part.toolCallId, part.args]), [['first', { value: 0 }], ['second', { value: 1 }]]); + assert.deepEqual((await result.response).messages[0].content, calls); + assert.equal(parts.at(-1).finishReason, 'tool-calls'); + assert.equal((await result.usage).totalTokens, 5); + assert.equal(requests.length, 1); + }); + + test(`${format}: abort while the consumer is paused stops the buffered tool batch`, async t => { + const wire = frames([...toolEvents(format, ['first', 'second']), ...ending(format)]); + const { baseUrl, requests } = await loopback(t, res => res.end(wire)); + const controller = new AbortController(), reason = new Error('fixture caller canceled'); + const result = stream(format, baseUrl, {}, controller.signal); + try { + assert.equal((await result.fullStream.next()).value.type, 'tool-call-streaming-start'); + controller.abort(reason); + await assert.rejects(result.fullStream.next(), error => error === reason); + await rejectedSlots(result, reason); + assert.equal(requests.length, 1); + } finally { await result.fullStream.return(); } + }); +} + +test('Messages rejects a terminal delimiter with no semantic stop reason', async t => { + const { baseUrl } = await loopback(t, res => res.end(frames([...toolEvents('anthropic'), ending('anthropic').at(-1)]))); + await rejectedTurn(stream('anthropic', baseUrl), /finish reason|stop reason|completion marker/i); +}); + +test('Chat accepts the completion markers and tool calls of lenient compatible endpoints', async t => { + const usage = { choices: [], usage: { prompt_tokens: 2, completion_tokens: 3 } }; + const emptyArgs = choice({ tool_calls: [{ index: 0, id: 'bare', function: { name: 'record', arguments: '' } }] }); + const cases = [ + ['[DONE] without a finish reason', [...toolEvents('openai'), usage, '[DONE]'], [['one', { value: 0 }]]], + ['a finish reason without [DONE]', [...toolEvents('openai'), choice({}, 'tool_calls'), usage], [['one', { value: 0 }]]], + ['"stop" after tool calls', [...toolEvents('openai'), choice({}, 'stop'), usage, '[DONE]'], [['one', { value: 0 }]]], + ['an empty argument string', [emptyArgs, choice({}, 'tool_calls'), usage, '[DONE]'], [['bare', {}]]], + ]; + for (const [label, events, expected] of cases) { + const { baseUrl } = await loopback(t, res => res.end(frames(events))); + const parts = await Array.fromAsync(stream('openai', baseUrl).fullStream); + assert.deepEqual(parts.filter(p => p.type === 'tool-call').map(p => [p.toolCallId, p.args]), expected, label); + } + const { baseUrl } = await loopback(t, res => res.end(frames([choice({ content: 'Done.' }), choice({}, 'eos'), '[DONE]']))); + const parts = await Array.fromAsync(stream('openai', baseUrl).fullStream); + assert.equal(parts.filter(p => p.type === 'text-delta').map(p => p.textDelta).join(''), 'Done.', 'an unlisted finish reason'); +}); + +test('Chat preserves in-stream provider errors and Retry-After after buffered arguments', async t => { + const { baseUrl, requests } = await loopback(t, res => { + res.setHeader('retry-after', '2'); + res.end(frames([...toolEvents('openai'), { error: { message: 'Synthetic throttle', status: 429, code: 'rate_limit_exceeded' } }])); + }); + await rejectedTurn(stream('openai', baseUrl), error => { + assert.equal(error.message, 'Synthetic throttle'); + assert.equal(error.code, 'rate_limit_exceeded'); + assert.equal(error.status, 429); + assert.equal(error.retryAfterMs, 2000); + }); + assert.equal(requests.length, 1); +}); + +test('Responses checks the terminal status before publishing any tool', async t => { + const { baseUrl } = await loopback(t, res => res.end(frames([...toolEvents('openai-responses'), + completed({ status: 'incomplete', incomplete_details: { reason: 'max_output_tokens' } })]))); + await rejectedTurn(stream('openai-responses', baseUrl), error => assert.equal(error.code, 'length')); +}); + +test('Responses reconciles the final snapshot without losing text or duplicating a tool', async t => { + const message = { type: 'message', id: 'msg', content: [{ type: 'output_text', text: 'partial reply' }] }; + const { baseUrl } = await loopback(t, res => res.end(frames([ + { type: 'response.output_item.added', output_index: 0, item: { type: 'message', id: 'msg' } }, + { type: 'response.output_text.delta', output_index: 0, delta: 'partial' }, + { type: 'response.output_item.done', output_index: 1, item: functionItem('first', 1) }, + completed({ output: [message, functionItem('first', 1), functionItem('second', 2)] }), + ]))); + const result = stream('openai-responses', baseUrl), parts = await Array.fromAsync(result.fullStream); + assert.equal(parts.filter(part => part.type === 'text-delta').map(part => part.textDelta).join(''), 'partial reply'); + assert.deepEqual(parts.filter(part => part.type === 'tool-call').map(part => part.toolCallId), ['first', 'second']); + assert.equal((await result.response).messages[0].content[0].text, 'partial reply'); +}); + +test('an unrelated HTTP 400 naming an absent option is not retried', async t => { + const { baseUrl, requests } = await loopback(t, res => { + res.writeHead(400); res.end(JSON.stringify({ error: { param: 'tools[0].parameters', message: 'Example mentions max_tokens' } })); + }); + await rejectedTurn(stream('openai', baseUrl), error => assert.equal(error.status, 400)); + assert.equal(requests.length, 1); +}); + +test('a recognized HTTP 400 fallback precedes the stream and publishes only one tool', async t => { + const { baseUrl, requests } = await loopback(t, (res, attempt) => { + if (attempt === 1) { res.writeHead(400); res.end(JSON.stringify({ error: { param: 'stream_options', message: 'Unsupported option' } })); } + else res.end(frames([...toolEvents('openai'), ...ending('openai')])); + }); + const parts = await Array.fromAsync(stream('openai', baseUrl).fullStream); + assert.equal(requests.length, 2); + assert.equal(requests[0].body.stream_options.include_usage, true); + assert.equal(requests[1].body.stream_options, undefined); + assert.deepEqual(parts.filter(part => part.type === 'tool-call').map(part => part.toolCallId), ['one']); +}); + +for (const phase of ['headers', 'SSE read', 'HTTP error body']) { + test(`a stalled ${phase} times out, closes the socket and does not retry`, async t => { + const closed = Promise.withResolvers(); + const { baseUrl, requests } = await loopback(t, res => { + res.on('close', closed.resolve); + if (phase !== 'headers') { res.writeHead(phase === 'SSE read' ? 200 : 400); res.write(phase === 'SSE read' ? 'data: ' : '{'); } + }); + const controller = new AbortController(); + const watchdog = setTimeout(() => controller.abort(new Error('test watchdog: upstream did not time out')), 1500); + try { + await rejectedTurn(stream('openai', baseUrl, { idleTimeoutMs: 200 }, controller.signal), error => assert.equal(error.name, 'TimeoutError')); + await closed.promise; + assert.equal(requests.length, 1); + assert.equal(getEventListeners(controller.signal, 'abort').length, 0); + } finally { clearTimeout(watchdog); } + }); +} + +test('backpressure does not pull extra chunks or count consumer delay as upstream idle', async t => { + const wire = [frame(choice({ content: 'one' })), frame(choice({ content: 'two' }, 'stop')), frame('[DONE]')]; + let pulls = 0, cancels = 0; + const body = new ReadableStream({ pull(controller) { controller.enqueue(Buffer.from(wire[pulls++])); }, cancel() { cancels++; } }, { highWaterMark: 0 }); + const result = stream('openai', 'http://127.0.0.1', { fetchImpl: () => new Response(body), idleTimeoutMs: 50 }); + t.after(() => result.fullStream.return()); + assert.equal((await result.fullStream.next()).value.textDelta, 'one'); + await delay(100); + assert.equal(pulls, 1); + const rest = await Array.fromAsync(result.fullStream); + assert.equal(rest[0].textDelta, 'two'); + assert.equal(rest.at(-1).type, 'finish'); + assert.equal(cancels, 1); + assert.equal(body.locked, false); +}); + +test('consumers stopping at finish leave no listeners and record usage exactly once per turn', async () => { + const controller = new AbortController(), streams = []; + let records = 0; + const session = createModelSession({ model: 'fixture', baseUrl: 'http://127.0.0.1', onUsage: () => { records++; }, + fetchImpl: () => new Response(frames([choice({ content: 'ok' }, 'stop'), { choices: [], usage: { prompt_tokens: 1 } }, '[DONE]'])) }); + try { + for (let n = 0; n < 64; n++) { + const result = session.getExecutor(history).stream({ signal: controller.signal }, `turn-${n}`, []); + streams.push(result.fullStream); + assert.equal((await result.fullStream.next()).value.type, 'text-delta'); + assert.equal((await result.fullStream.next()).value.type, 'finish'); + await tick(); + assert.equal(getEventListeners(controller.signal, 'abort').length, 0, `turn ${n}`); + assert.equal(records, n + 1); + } + } finally { await Promise.all(streams.map(iterator => iterator.return())); } + assert.equal(records, 64); +}); + +test('SSE bounds one pending frame, not the total size of a healthy stream', async () => { + const body = new Response('data: 1234567890\n'.repeat(3) + '\n').body; + await assert.rejects(Array.fromAsync(readSse(body, { maxEventChars: 32 })), /SSE event.*limit/i); + assert.equal(body.locked, false); + const many = new Response('data: abc\r\r'.repeat(50)).body; + assert.deepEqual(await Array.fromAsync(readSse(many, { maxEventChars: 32 })), Array(50).fill('abc')); +}); + +test('SSE preserves multibyte UTF-8, split CRLF, comments and multiline data', async () => { + const bytes = Buffer.from(': ping\r\nevent: fixture\r\ndata: {\r\ndata: "word": "\u6d41"}\r\n\r\ndata: trailing'); + const body = new ReadableStream({ start(controller) { + for (const byte of bytes) controller.enqueue(Uint8Array.of(byte)); + controller.close(); + } }); + assert.deepEqual(await Array.fromAsync(readSse(body)), ['{\n"word": "\u6d41"}']); + assert.equal(body.locked, false); +}); + +for (const format of API_FORMATS) { + test(`${format}: a socket reset after visible text and buffered tool data is not replayed`, async t => { + let socket; + const text = format === 'openai' ? choice({ content: 'visible' }) : format === 'openai-responses' + ? { type: 'response.output_text.delta', output_index: 1, delta: 'visible' } + : { type: 'content_block_start', index: 1, content_block: { type: 'text', text: 'visible' } }; + const { baseUrl, requests } = await loopback(t, res => { + socket = res.socket; res.write(frames([...toolEvents(format), text])); + }); + const result = stream(format, baseUrl); + assert.equal((await result.fullStream.next()).value.textDelta, 'visible'); + socket.destroy(); + await rejectedTurn(result, error => assert.ok(error instanceof Error)); + assert.equal(requests.length, 1); + }); +} + +test('return while a body read is pending closes the upstream and rejects every slot', async t => { + const sent = Promise.withResolvers(), closed = Promise.withResolvers(); + const { baseUrl, requests } = await loopback(t, res => { + res.on('close', closed.resolve); res.write(': waiting\n\n'); sent.resolve(); + }); + const controller = new AbortController(), result = stream('openai', baseUrl, {}, controller.signal); + const pending = assert.rejects(result.fullStream.next(), { name: 'AbortError' }); + await sent.promise; + await result.fullStream.return(); + await pending; + await closed.promise; + for (const key of slots) await assert.rejects(result[key], { name: 'AbortError' }); + assert.equal(getEventListeners(controller.signal, 'abort').length, 0); + assert.equal(requests.length, 1); +}); + +test('caller cancellation while reading an HTTP 400 body wins over fallback', async t => { + const sent = Promise.withResolvers(); + const { baseUrl, requests } = await loopback(t, res => { + res.writeHead(400); res.write('{"error":'); sent.resolve(); + }); + const controller = new AbortController(), reason = new Error('caller stopped a pending rejection'); + const result = stream('openai', baseUrl, {}, controller.signal); + const done = rejectedTurn(result, error => assert.equal(error, reason)); + await sent.promise; + controller.abort(reason); + await done; + assert.equal(requests.length, 1); +}); + +test('upstream activity keeps a long turn alive beyond one idle interval', async t => { + // Isolate the per-read deadline from the cost of the first real TCP request on emulated CPUs. + // The separate stalled-header/body tests exercise real sockets and cancellation. + t.mock.timers.enable({ apis: ['setTimeout'] }); + let wire, read = Promise.withResolvers(); + const body = new ReadableStream({ start(c) { wire = c; }, pull() { read.resolve(); } }, { highWaterMark: 0 }); + const result = stream('openai', 'http://127.0.0.1', { fetchImpl: () => new Response(body), idleTimeoutMs: 200 }); + t.after(() => result.fullStream.return()); + for (let n = 0; n < 8; n++) { + const next = result.fullStream.next(); + await read.promise; read = Promise.withResolvers(); + t.mock.timers.tick(199); + wire.enqueue(Buffer.from(frame(choice({ content: 'x' })))); + assert.equal((await next).value.textDelta, 'x'); + } + const end = result.fullStream.next(); + await read.promise; + t.mock.timers.tick(199); + wire.enqueue(Buffer.from(frames([choice({}, 'stop'), '[DONE]']))); + assert.equal((await end).value.type, 'finish'); +}); + +test('Responses argument completion fills a missing suffix without inventing empty arguments', async t => { + const item = functionItem('only', 1); + const { baseUrl } = await loopback(t, res => res.end(frames([ + { type: 'response.output_item.added', output_index: 0, item: { ...item, arguments: '' } }, + { type: 'response.function_call_arguments.delta', output_index: 0, delta: '{' }, + { type: 'response.function_call_arguments.done', output_index: 0, arguments: item.arguments }, + completed({}), + ]))); + const parts = await Array.fromAsync(stream('openai-responses', baseUrl).fullStream); + assert.deepEqual(parts.filter(part => part.type === 'tool-call').map(part => part.args), [{ value: 1 }]); +}); + +test('Responses does not execute a streamed item that is missing from the final snapshot', async t => { + const { baseUrl } = await loopback(t, res => res.end(frames([...toolEvents('openai-responses'), completed({ output: [] })]))); + await rejectedTurn(stream('openai-responses', baseUrl), /snapshot|output item/i); +}); + +test('Responses rejects conflicting item identities in the final snapshot', async t => { + const { baseUrl } = await loopback(t, res => res.end(frames([...toolEvents('openai-responses'), + completed({ output: [functionItem('different', 0)] })]))); + await rejectedTurn(stream('openai-responses', baseUrl), /conflict/i); +}); + +test('missing OpenAI function arguments become {} only for a tool that requires none', async t => { + const required = [{ name: 'record', parameters: { type: 'object', properties: { value: { type: 'integer' } }, required: ['value'] } }]; + for (const format of ['openai', 'openai-responses']) { + const item = format === 'openai' ? choice({ tool_calls: [{ index: 0, id: 'missing', function: { name: 'record' } }] }) + : { type: 'response.output_item.done', output_index: 0, item: { ...functionItem('missing', 0), arguments: '' } }; + const { baseUrl } = await loopback(t, res => res.end(frames([item, ...ending(format)]))); + const strict = createModelSession({ model: 'fixture', apiFormat: format, baseUrl }) + .getExecutor(history).stream({}, 'fixture-turn', required); + await rejectedTurn(strict, /tool arguments/i); + const parts = await Array.fromAsync(stream(format, baseUrl).fullStream); + assert.deepEqual(parts.filter(p => p.type === 'tool-call').map(p => p.args), [{}], format); + } +}); + +test('Messages keeps complete initial tool input even without JSON deltas', async t => { + const { baseUrl } = await loopback(t, res => res.end(frames([ + { type: 'message_start', message: { id: 'msg' } }, + { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'one', name: 'record', input: { value: 7 } } }, + { type: 'content_block_stop', index: 0 }, ...ending('anthropic'), + ]))); + const parts = await Array.fromAsync(stream('anthropic', baseUrl).fullStream); + assert.deepEqual(parts.filter(part => part.type === 'tool-call').map(part => part.args), [{ value: 7 }]); +}); + +test('a model-specific fallback does not disable options for another selected model', async t => { + const { baseUrl, requests } = await loopback(t, (res, n) => { + if (n === 1) { res.writeHead(400); res.end(JSON.stringify({ error: { param: 'stream_options', message: 'Unsupported option' } })); } + else res.end(frames([choice({ content: 'ok' }, 'stop'), '[DONE]'])); + }); + let model = 'first'; + const session = createModelSession({ baseUrl, model, selectRequest: () => ({ model }) }); + for (model of ['first', 'other', 'first']) await Array.fromAsync(session.getExecutor(history).stream({}, 'test', []).fullStream); + assert.deepEqual(requests.map(r => [r.body.model, !!r.body.stream_options]), + [['first', true], ['first', false], ['other', true], ['first', false]]); +}); + +test('a rejected output option does not discard valid replay or move a tool screenshot', async t => { + const messages = [...history, { role: 'assistant', content: [ + { type: 'reasoning', text: 'fixture', signature: 'synthetic-item', providerOptions: { grokbot: { format: 'openai-responses', model: 'fixture' } } }, + { type: 'tool-call', toolCallId: 'old', toolName: 'record', args: { value: 1 } }, + ] }, { role: 'tool', content: [{ type: 'tool-result', toolCallId: 'old', result: 'fixture', + experimental_content: [{ type: 'image', data: 'AA==', mimeType: 'image/png' }] }] }]; + const { baseUrl, requests } = await loopback(t, (res, n) => { + const param = n === 1 ? 'reasoning.summary' : n === 2 ? 'max_output_tokens' : undefined; + if (param) { res.writeHead(400); res.end(JSON.stringify({ error: { param, message: `Unsupported parameter: ${param}` } })); } + else res.end(frame(completed({}))); + }); + const session = createModelSession({ baseUrl, model: 'fixture', apiFormat: 'openai-responses' }); + await Array.fromAsync(session.getExecutor(messages).stream({}, 'fixture', tools, { maxTokens: 200 }).fullStream); + assert.equal(requests.length, 3); + assert.deepEqual(requests[1].body.input, requests[0].body.input); + assert.deepEqual(requests[2].body.input, requests[0].body.input); + assert.equal(requests[1].body.reasoning?.summary, undefined); + assert.equal(requests[2].body.max_output_tokens, undefined); +}); + +test('a corrupt UTF-8 byte in tool arguments is not silently replaced and executed', async t => { + const wire = Buffer.from(frames([choice({ tool_calls: [{ index: 0, id: 'one', function: { name: 'record', arguments: '{"value":"MARK"}' } }] }), + ...ending('openai')])); + wire[wire.indexOf('MARK')] = 0xff; + const { baseUrl, requests } = await loopback(t, res => res.end(wire)); + await rejectedTurn(stream('openai', baseUrl), /UTF-8|utf-8/); + assert.equal(requests.length, 1); +}); diff --git a/host/tests/model-tool-order-regression.test.mjs b/host/tests/model-tool-order-regression.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..14bfbd9cd1cf3ae46817364cea615d4fb82da470 --- /dev/null +++ b/host/tests/model-tool-order-regression.test.mjs @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { setImmediate as tick } from 'node:timers/promises'; +import { createModelSession } from '../runtime/model-session.mjs'; +import { awaitToolCallTurn, recordToolCallOrder } from '../runtime/reliability/tool-order.mjs'; + +const call = id => ({ toolName: 'SendToUser', toolCallId: id }); + +test('abandoning a streamed tool batch releases only the calls not handed to the Harness', async () => { + const ids = ['delivered-first', 'delivered-second', 'never-delivered']; + const data = { choices: [{ delta: { tool_calls: ids.map((id, index) => ({ id, index, + function: { name: 'SendToUser', arguments: '{}' } })) }, finish_reason: 'tool_calls' }] }; + const session = createModelSession({ model: 'fixture', baseUrl: 'http://127.0.0.1', + fetchImpl: () => new Response(`data: ${JSON.stringify(data)}\n\ndata: [DONE]\n\n`) }); + const controller = new AbortController(); + const result = session.getExecutor([{ role: 'user', content: 'fixture' }]).stream({ signal: controller.signal }, 'turn', []); + const releases = []; + try { + for (let i = 0; i < 2; i++) { + assert.equal((await result.fullStream.next()).value.type, 'tool-call-streaming-start'); + assert.equal((await result.fullStream.next()).value.type, 'tool-call-delta'); + assert.equal((await result.fullStream.next()).value.toolCallId, ids[i]); + } + assert.equal((await result.fullStream.next()).value.type, 'tool-call-streaming-start'); + controller.abort(); + await result.fullStream.return(); + let secondReady = false, thirdReady = false; + const second = awaitToolCallTurn(ids[1], undefined, { maxWaitMs: 1000 }).then(release => { secondReady = true; releases.push(release); }); + const third = awaitToolCallTurn(ids[2], undefined, { maxWaitMs: 1000 }).then(release => { thirdReady = true; releases.push(release); }); + await tick(); + const before = [secondReady, thirdReady]; + (await awaitToolCallTurn(ids[0]))(); + await second; + releases.forEach(release => release()); + await third; + assert.deepEqual(before, [false, true], 'only the already delivered second message should still wait'); + } finally { + releases.forEach(release => release()); + await result.fullStream.return(); + } +}); + +test('unclaimed ordering entries expire during an idle period without another model turn', async t => { + t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1000 }); + const ids = ['idle-first', 'idle-next']; + recordToolCallOrder(ids.map(call)); + t.mock.timers.tick(10 * 60_000 + 1); + let ready = false; + const waiting = awaitToolCallTurn(ids[1], undefined, { maxWaitMs: 500 }).then(release => { ready = true; release(); }); + await tick(); + const atExpiry = ready; + (await awaitToolCallTurn(ids[0]))(); + await waiting; + assert.equal(atExpiry, true, 'an expired predecessor must not start a fresh wait'); +}); + +test('a concurrent response cannot take over a live ordered call ID, and neither turn fails', async () => { + recordToolCallOrder(['before-shared', 'live-shared'].map(call)); + recordToolCallOrder(['new-head', 'live-shared'].map(call)); + // The ambiguous ID waits on neither head: the first response's predecessor is still running. + const releaseHead = await awaitToolCallTurn('before-shared'); + const started = Date.now(); + (await awaitToolCallTurn('live-shared', undefined, { maxWaitMs: 5000 }))(); + assert.ok(Date.now() - started < 1000); + releaseHead(); (await awaitToolCallTurn('new-head'))(); + recordToolCallOrder([call('live-shared')]); + (await awaitToolCallTurn('live-shared'))(); +}); diff --git a/host/tests/prompt-runtime.test.mjs b/host/tests/prompt-runtime.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..633a6e17208a41c8b217e48356951bd2e490a42c --- /dev/null +++ b/host/tests/prompt-runtime.test.mjs @@ -0,0 +1,66 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { installLocalPromptPolicy } from '../runtime/prompt-runtime.mjs'; + +test('parent prompts preserve proactive memory retrieval and reject stale access conclusions', async t => { + const directory = await mkdtemp(join(tmpdir(), 'prompt-runtime-')); + const previous = globalThis.__grokbotPromptPolicy; + const runtime = await installLocalPromptPolicy(directory, {}, { + pollMs: 60_000, memoryRoot: '/data/runtime/host-data/', memoryMounts: true, + }); + t.after(async () => { + await runtime.close(); + if (previous === undefined) delete globalThis.__grokbotPromptPolicy; + else globalThis.__grokbotPromptPolicy = previous; + await rm(directory, { recursive: true, force: true }); + }); + + const render = globalThis.__grokbotPromptPolicy.snapshot(); + const parent = render('parent', 'Original parent prompt'); + assert.match(parent, /^Original parent prompt\n\nMemory access is configured for this turn:/); + assert.match(parent, /agent memory is mounted at \/data\/runtime\/host-data\/agents/); + assert.match(parent, /shared user memory at \/data\/runtime\/host-data\/user-memory/); + assert.match(parent, /Use memory proactively whenever it can affect the answer, without waiting for the user to ask/); + assert.match(parent, /when you need older or omitted facts, inspect the corresponding files with Read or Shell/); + assert.match(parent, /Do not repeat an earlier turn's "not mounted" or "not readable" result/); + assert.match(parent, /A missing monthly log means that no file has been recorded for that month yet/); + assert.doesNotMatch(parent, /When asked to read, search, audit, clean, or summarize memory/); + assert.equal(render('automation', 'Original automation prompt'), 'Original automation prompt'); +}); + +test('remote execution topologies do not receive the local memory directive', async t => { + const directory = await mkdtemp(join(tmpdir(), 'prompt-runtime-')); + const previous = globalThis.__grokbotPromptPolicy; + const runtime = await installLocalPromptPolicy(directory, {}, { pollMs: 60_000, memoryMounts: false }); + t.after(async () => { + await runtime.close(); + if (previous === undefined) delete globalThis.__grokbotPromptPolicy; + else globalThis.__grokbotPromptPolicy = previous; + await rm(directory, { recursive: true, force: true }); + }); + + const render = globalThis.__grokbotPromptPolicy.snapshot(); + assert.equal(render('parent', 'Original parent prompt'), 'Original parent prompt'); +}); + +test('an almost-full parent prompt falls back when the memory directive would exceed the limit', async t => { + const directory = await mkdtemp(join(tmpdir(), 'prompt-runtime-')); + const previous = globalThis.__grokbotPromptPolicy; + const runtime = await installLocalPromptPolicy(directory, {}, { + pollMs: 60_000, memoryRoot: '/data/runtime/host-data', memoryMounts: true, + }); + t.after(async () => { + await runtime.close(); + if (previous === undefined) delete globalThis.__grokbotPromptPolicy; + else globalThis.__grokbotPromptPolicy = previous; + await rm(directory, { recursive: true, force: true }); + }); + + const original = `Memory prompt\n${'x'.repeat(199_900)}`; + assert.ok(Buffer.byteLength(original) < 200_000); + const render = globalThis.__grokbotPromptPolicy.snapshot(); + assert.equal(render('parent', original), original); +}); diff --git a/host/tests/storage.test.mjs b/host/tests/storage.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b7d7f6b57cea0186bef3b9fc78fdb78b6b9a2e98 --- /dev/null +++ b/host/tests/storage.test.mjs @@ -0,0 +1,24 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { syncRenamedDirectory } from '../server/storage.mjs'; + +function handle(sync) { + let closed = false; + return { sync, close: async () => { closed = true; }, get closed() { return closed; } }; +} + +test('Windows accepts EPERM only when syncing a renamed directory', async () => { + const error = Object.assign(new Error('directory fsync is unsupported'), { code: 'EPERM' }); + const directory = handle(async () => { throw error; }); + await syncRenamedDirectory('fixture', { platform: 'win32', openFile: async () => directory }); + assert.equal(directory.closed, true); +}); + +test('directory sync failures remain fatal on other platforms and error codes', async () => { + for (const [platform, code] of [['linux', 'EPERM'], ['win32', 'EIO']]) { + const error = Object.assign(new Error('sync failure'), { code }); + const directory = handle(async () => { throw error; }); + await assert.rejects(syncRenamedDirectory('fixture', { platform, openFile: async () => directory }), error); + assert.equal(directory.closed, true); + } +}); diff --git a/host/tests/tool-order.test.mjs b/host/tests/tool-order.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c4f193bff3fc44f3e7280c1564f36e15ac1c8a75 --- /dev/null +++ b/host/tests/tool-order.test.mjs @@ -0,0 +1,75 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { awaitToolCallTurn, recordToolCallOrder } from '../runtime/reliability/tool-order.mjs'; +import { serializeToolCalls } from '../runtime/model-common.mjs'; + +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); +const call = (toolCallId, toolName) => ({ type: 'tool-call', toolCallId, toolName, args: {} }); + +/** Run like the journal does: wait for the turn, execute, release. */ +async function run(id, log, ms, signal) { + const release = await awaitToolCallTurn(id, signal); + try { log.push(`start ${id}`); await delay(ms); log.push(`end ${id}`); } + finally { release(); } +} + +test('messages from one response run in written order even when started in reverse', async () => { + serializeToolCalls([call('m1', 'SendToUser'), call('s1', 'WebSearch'), call('m2', 'SendToUser'), call('m3', 'SendToAgent')]); + const log = []; + // The longest message is written first; later ones start earlier and would finish first. + await Promise.all([run('m3', log, 1), run('m2', log, 1), run('s1', log, 30), run('m1', log, 20)]); + const messages = log.filter(line => line.startsWith('start m')); + assert.deepEqual(messages, ['start m1', 'start m2', 'start m3']); + // Each message starts only after the previous one finished. + assert.ok(log.indexOf('end m1') < log.indexOf('start m2')); + assert.ok(log.indexOf('end m2') < log.indexOf('start m3')); + // Other tools are not delayed by messages. + assert.equal(log[0], 'start s1'); +}); + +test('separate responses and unrecorded calls do not wait', async () => { + recordToolCallOrder([{ toolCallId: 'a1', toolName: 'SendToUser' }]); + recordToolCallOrder([{ toolCallId: 'b1', toolName: 'SendToUser' }]); + const log = []; + await Promise.all([run('b1', log, 1), run('a1', log, 10), run('unknown', log, 1)]); + assert.equal(log.indexOf('start b1') < log.indexOf('end a1'), true); + assert.ok(log.includes('start unknown')); +}); + +test('a predecessor that never runs only delays the next message up to the limit', async () => { + recordToolCallOrder([{ toolCallId: 'lost', toolName: 'SendToUser' }, { toolCallId: 'next', toolName: 'SendToUser' }]); + const started = Date.now(); + const release = await awaitToolCallTurn('next', undefined, { maxWaitMs: 50 }); + release(); + assert.ok(Date.now() - started >= 45); + (await awaitToolCallTurn('lost'))(); +}); + +test('an ID reused by a concurrent response runs unordered instead of failing either turn', async () => { + recordToolCallOrder([{ toolCallId: 'call_0', toolName: 'SendToUser' }, { toolCallId: 'x-after', toolName: 'SendToUser' }]); + recordToolCallOrder([{ toolCallId: 'y-before', toolName: 'SendToUser' }, { toolCallId: 'call_0', toolName: 'SendToUser' }, + { toolCallId: 'y-after', toolName: 'SendToUser' }]); + const log = []; + // Neither response waits on the other's call_0; each keeps its own remaining order. + await Promise.all([run('y-after', log, 1), run('call_0', log, 1), run('x-after', log, 1), run('y-before', log, 20)]); + assert.ok(log.indexOf('end y-before') < log.indexOf('start y-after')); + assert.ok(log.indexOf('start x-after') < log.indexOf('end y-before'), 'the first response is not held by the second'); + recordToolCallOrder([{ toolCallId: 'call_0', toolName: 'SendToUser' }]); + const started = Date.now(); + (await awaitToolCallTurn('call_0'))(); + assert.ok(Date.now() - started < 1000); + assert.throws(() => recordToolCallOrder([{ toolCallId: 'twice', toolName: 'SendToUser' }, { toolCallId: 'twice', toolName: 'SendToUser' }]), + /repeated in one response/); +}); + +test('cancellation stops waiting for an earlier message', async () => { + recordToolCallOrder([{ toolCallId: 'first', toolName: 'SendToUser' }, { toolCallId: 'second', toolName: 'SendToUser' }]); + const controller = new AbortController(); + const releaseFirst = await awaitToolCallTurn('first'); + const waiting = awaitToolCallTurn('second', controller.signal); + setTimeout(() => controller.abort(), 10); + const started = Date.now(); + (await waiting)(); + assert.ok(Date.now() - started < 1000); + releaseFirst(); +}); diff --git a/host/tests/web-client.test.mjs b/host/tests/web-client.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..61f4aeb6769245a9c0a4930ba1e8aa2633847b1d --- /dev/null +++ b/host/tests/web-client.test.mjs @@ -0,0 +1,290 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, readdir, rm } from 'node:fs/promises'; +import http from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { crc32, deflateRawSync } from 'node:zlib'; +import { Auth } from '../server/auth.mjs'; +import { BUNDLE_SCHEMA, WebClient, bundlePath, readBundleZip, verifyBundle, webManifest } from '../server/web-client.mjs'; + +const REQUIRED = ['renderer/index.html', 'client/boot-data.js', 'client/compat.js', 'client/bridge.js', 'client/native.js', + 'client/web-shell.js', 'client/official-preload.js', 'client/vnc-bridge.js', 'client/vnc-preload.js', 'client/icon.png']; +const sha = bytes => createHash('sha256').update(bytes).digest('hex'); + +/** A minimal ZIP writer: stored or deflated entries, as web/patchers/patch.mjs produces. */ +function zip(entries) { + const parts = [], central = []; + let offset = 0; + for (const [name, data, deflate = false] of entries) { + const nameBytes = Buffer.from(name), body = deflate ? deflateRawSync(data) : data; + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(deflate ? 8 : 0, 8); + local.writeUInt32LE(crc32(data), 14); local.writeUInt32LE(body.length, 18); local.writeUInt32LE(data.length, 22); + local.writeUInt16LE(nameBytes.length, 26); + const entry = Buffer.alloc(46); + entry.writeUInt32LE(0x02014b50, 0); entry.writeUInt16LE(20, 4); entry.writeUInt16LE(20, 6); entry.writeUInt16LE(deflate ? 8 : 0, 10); + entry.writeUInt32LE(crc32(data), 16); entry.writeUInt32LE(body.length, 20); entry.writeUInt32LE(data.length, 24); + entry.writeUInt16LE(nameBytes.length, 28); entry.writeUInt32LE(offset, 42); + parts.push(local, nameBytes, body); central.push(entry, nameBytes); + offset += 30 + nameBytes.length + body.length; + } + const directory = Buffer.concat(central), end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10); + end.writeUInt32LE(directory.length, 12); end.writeUInt32LE(offset, 16); + return Buffer.concat([...parts, directory, end]); +} + +function bundleFiles(version = '1.1.0') { + const files = new Map(REQUIRED.map(name => [name, Buffer.from(`/* ${name} */`)])); + files.set('renderer/index.html', Buffer.from(`Demo ${version}`)); + files.set('renderer/assets/index-demo.js', Buffer.from('console.log("demo");\n'.repeat(200))); + return files; +} +function bundle(files = bundleFiles(), { version = '1.1.0', manifestFiles } = {}) { + const manifest = { schema: BUNDLE_SCHEMA, rendererVersion: version, recommended: true, builtAt: '2026-01-01T00:00:00.000Z', + files: manifestFiles ?? Object.fromEntries([...files].map(([name, bytes]) => [name, { bytes: bytes.length, sha256: sha(bytes) }])) }; + return zip([['web-bundle.json', Buffer.from(JSON.stringify(manifest))], ...[...files].map(([name, bytes]) => [name, bytes, bytes.length > 512])]); +} + +async function fixture(t) { + const dir = await mkdtemp(join(tmpdir(), 'grokbot-web-test-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const auth = await new Auth(dir).load(); + const web = await new WebClient(dir, { auth }).load(); + return { dir, auth, web }; +} + +test('bundle paths stay inside renderer/ and client/', () => { + for (const name of ['renderer/index.html', 'client/desktop/workspace.css', 'renderer/assets/a@2x~b+c.png']) + assert.equal(bundlePath(name), name); + for (const name of ['web-bundle.json', '../renderer/x', 'renderer/../client/x', 'renderer//x', 'renderer/./x', '/renderer/x', + 'renderer\\x', 'renderer/x y', 'other/x', 'renderer/', 'client/%2e%2e/x', `renderer/${'a'.repeat(600)}`, 7]) + assert.equal(bundlePath(name), null, String(name)); +}); + +test('bundle ZIPs are read with every entry checked against the manifest', () => { + const files = bundleFiles(), bytes = bundle(files); + const entries = readBundleZip(bytes); + assert.equal(entries.size, files.size + 1); + assert.deepEqual(entries.get('renderer/assets/index-demo.js'), files.get('renderer/assets/index-demo.js')); + assert.equal(verifyBundle(entries).rendererVersion, '1.1.0'); + + const corrupt = Buffer.from(bytes); + corrupt[bytes.indexOf('/* client/bridge.js */') + 3] ^= 1; + assert.throws(() => readBundleZip(corrupt), /校验失败/); + assert.throws(() => readBundleZip(Buffer.from('not a zip at all, just text padding the length')), /ZIP 目录无效/); + assert.throws(() => readBundleZip(zip([['web-bundle.json', Buffer.from('{}')], ['../evil.js', Buffer.from('x')]])), /路径无效/); + assert.throws(() => readBundleZip(zip([['web-bundle.json', Buffer.from('{}')], ['client/a.js', Buffer.from('1')], ['client/a.js', Buffer.from('2')]])), /路径重复/); + + const changed = new Map(files); changed.set('client/bridge.js', Buffer.from('changed')); + const manifestFiles = Object.fromEntries([...files].map(([name, data]) => [name, { bytes: data.length, sha256: sha(data) }])); + assert.throws(() => verifyBundle(readBundleZip(bundle(changed, { manifestFiles }))), /与清单不一致:client\/bridge\.js/); + const extra = new Map(files); extra.set('client/extra.js', Buffer.from('extra')); + assert.throws(() => verifyBundle(readBundleZip(bundle(extra, { manifestFiles }))), /与清单不一致/); + const missing = new Map(files); missing.delete('client/web-shell.js'); + assert.throws(() => verifyBundle(readBundleZip(bundle(missing))), /缺少 client\/web-shell\.js/); + assert.throws(() => verifyBundle(readBundleZip(bundle(files, { version: 'latest' }))), /版本无效/); + assert.throws(() => verifyBundle(readBundleZip(zip([['web-bundle.json', Buffer.from('{"schema":"other"}')], ['client/a.js', Buffer.from('a')]]))), /格式不受支持/); + assert.throws(() => verifyBundle(new Map([['client/a.js', Buffer.from('a')]])), /缺少 web-bundle\.json/); +}); + +test('installing enables the first bundle, serves it compressed and keeps the choice on replacement', async t => { + const { dir, auth, web } = await fixture(t); + assert.deepEqual([web.installed, web.available], [false, false]); + await assert.rejects(web.setEnabled(true), /请先上传/); + const status = await web.install(bundle()); + assert.deepEqual([status.installed, status.enabled, status.rendererVersion, status.files], [true, true, '1.1.0', REQUIRED.length + 1]); + assert.equal(webManifest().start_url, '/web/'); + + const server = http.createServer((request, response) => web.serve(request, response, decodeURIComponent(request.url.slice(1))) + .catch(error => { response.writeHead(error.status ?? 500); response.end(); })); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise(resolve => server.close(resolve))); + const base = `http://127.0.0.1:${server.address().port}/`; + const asset = await fetch(base + 'renderer/assets/index-demo.js'); + assert.equal(asset.status, 200); + assert.equal(asset.headers.get('content-encoding'), 'gzip'); + assert.equal(asset.headers.get('cross-origin-resource-policy'), 'same-origin'); + assert.match(asset.headers.get('cache-control'), /immutable/); + assert.equal(await asset.text(), 'console.log("demo");\n'.repeat(200)); + const page = await fetch(base + 'renderer/index.html'); + assert.equal(page.headers.get('cache-control'), 'private, no-cache'); + assert.match(page.headers.get('content-type'), /^text\/html/); + assert.equal((await fetch(base + 'renderer/index.html', { headers: { 'if-none-match': page.headers.get('etag') } })).status, 304); + assert.equal((await fetch(base + 'renderer/missing.js')).status, 404); + + await web.setEnabled(false); + const second = await web.install(bundle(bundleFiles('1.2.0'), { version: '1.2.0' })); + assert.deepEqual([second.enabled, second.rendererVersion], [false, '1.2.0']); + assert.match(await (await fetch(base + 'renderer/index.html')).text(), /Demo 1\.2\.0/); + assert.deepEqual((await readdir(join(dir, 'web-client'))).sort(), ['current']); + await assert.rejects(web.install(Buffer.from('broken')), /大小无效|ZIP/); + assert.equal(web.status().rendererVersion, '1.2.0', 'a rejected upload keeps the installed bundle'); + + // A restart after an interrupted upload removes what the upload left behind. + await mkdir(join(dir, 'web-client', 'stage-0123456789ab')); + const reloaded = await new WebClient(dir, { auth }).load(); + assert.deepEqual((await readdir(join(dir, 'web-client'))).sort(), ['current']); + assert.equal(reloaded.status().rendererVersion, '1.2.0'); + assert.equal((await reloaded.remove()).installed, false); + assert.equal(existsSync(join(dir, 'web-client', 'current')), false); +}); + +test('the browser cookie is a device token only for web devices, with the header and the Host origin', async t => { + const { auth, web } = await fixture(t); + await web.install(bundle()); + const { pairingKey } = await auth.createPairing(); + const browser = await auth.pair({ pairingKey, deviceName: 'Web client · Demo' }, { web: true }); + assert.equal(auth.authenticate(browser.token).platform, 'web'); + const desktopKey = (await auth.createPairing()).pairingKey; + const desktop = await auth.pair({ pairingKey: desktopKey, deviceName: 'Demo Mac', platform: 'desktop' }); + await assert.rejects(auth.pair({ pairingKey: (await auth.createPairing()).pairingKey, deviceName: 'Demo' }), /desktop 或 ios/); + assert.equal(auth.authenticate((await auth.addWebDevice('Admin browser')).token).platform, 'web'); + + const origin = 'https://host.example'; + const request = (token, headers = {}) => ({ headers: { cookie: `other=1; grokbot_web=${token}`, ...headers } }); + assert.equal(web.browserDevice(request(browser.token)).device.id, browser.deviceId); + assert.equal(web.browserDevice(request(desktop.token)), null, 'a desktop token in the cookie is not a browser sign-in'); + assert.equal(web.deviceToken(request(browser.token, { 'x-grokbot-web': '1', origin }), origin), browser.token); + assert.equal(web.deviceToken(request(browser.token, { 'x-grokbot-web': '1' }), origin), browser.token); + assert.throws(() => web.deviceToken(request(browser.token), origin), /请从网页版发起请求/); + assert.throws(() => web.deviceToken(request(browser.token, { 'x-grokbot-web': '1', origin: 'https://evil.example' }), origin), /来源不匹配/); + assert.equal(web.deviceToken({ headers: { authorization: 'Bearer app', cookie: `grokbot_web=${browser.token}` } }, origin), null, + 'apps keep using their bearer token'); + assert.equal(web.deviceToken({ headers: {} }, origin), null); + + assert.match(web.sessionCookie(browser.token, origin), /^grokbot_web=[^;]+; Path=\/; HttpOnly; SameSite=Strict; Max-Age=\d+; Secure$/); + assert.doesNotMatch(web.sessionCookie(browser.token, 'http://192.0.2.1'), /Secure/); + assert.match(web.sessionCookie('', origin), /Max-Age=0/); + + await web.setEnabled(false); + assert.equal(web.browserDevice(request(browser.token)), null); + assert.throws(() => web.deviceToken(request(browser.token, { 'x-grokbot-web': '1' }), origin), /网页版未启用/); +}); + +test('the noVNC page gains the computer-view bridge from the installed bundle', async t => { + const { web } = await fixture(t); + await web.install(bundle()); + assert.equal(WebClient.injectVncBridge('x', '/vnc/desktop'), + '' + + 'x'); + assert.match(WebClient.injectVncBridge('

no head

', '/vnc/fork'), /^ diff --git a/mac/clients/desktop/connect.js b/mac/clients/desktop/connect.js index da26e3fe4da2e71ec70fbabfac55ee5deb9f5081..0bbf0e66619d7de29f3d058131c5cc5120addb42 100644 --- a/mac/clients/desktop/connect.js +++ b/mac/clients/desktop/connect.js @@ -1,11 +1,13 @@ import { grokText as text } from './i18n.mjs'; +import { normalizePairingCode } from './pairing-code.mjs'; const server = document.querySelector('#server'); const tailcat = document.querySelector('#tailcat'); -tailcat.onchange = () => { server.placeholder = tailcat.checked ? 'tailcat://connect/…' : 'https://bot.example.com'; }; const key = document.querySelector('#key'); const status = document.querySelector('#status'); const connect = document.querySelector('#connect'); const disconnect = document.querySelector('#disconnect'); +let saved = null; +const canRetry = () => Boolean(saved && server.value === saved.server && tailcat.checked === saved.tailcat); document.documentElement.lang = /^zh/i.test(window.connection.locale) ? 'zh-CN' : 'en'; document.title = text('连接 Grok Bot', 'Connect Grok Bot'); document.querySelector('h1').textContent = text('连接你的 Grok Bot', 'Connect your Grok Bot'); @@ -13,25 +15,43 @@ document.querySelector('[for=server]').textContent = text('Host 地址', 'Host a document.querySelector('[for=key]').textContent = text('配对码', 'Pairing code'); key.placeholder = text('配对码', 'Pairing code'); connect.textContent = text('连接', 'Connect'); -key.addEventListener('input', () => { key.value = key.value.toUpperCase(); }); +const updateRetry = () => { + const retry = canRetry(); + key.required = !retry; + key.placeholder = retry ? text('可留空以重新连接', 'Leave blank to reconnect') : text('配对码', 'Pairing code'); + if (saved) connect.textContent = retry && !key.value ? text('重新连接', 'Reconnect') : text('重新配对', 'Pair again'); +}; +tailcat.onchange = () => { server.placeholder = tailcat.checked ? 'tailcat://connect/…' : 'https://bot.example.com'; updateRetry(); }; +server.addEventListener('input', updateRetry); +const tidyKey = () => { key.value = normalizePairingCode(key.value); updateRetry(); }; +key.addEventListener('input', event => { if (!event.isComposing) tidyKey(); }); +key.addEventListener('compositionend', tidyKey); disconnect.textContent = text('退出连接', 'Disconnect'); window.connection.status().then(result => { + saved = result.paired && !result.connected ? result : null; server.value = result.server ?? ''; tailcat.checked = result.tailcat === true; tailcat.onchange(); - disconnect.hidden = !result.connected; + disconnect.hidden = !result.paired; if (result.error) status.textContent = result.error; if (result.connected) connect.textContent = text('重新配对', 'Pair again'); -}); +}).catch(error => { status.textContent = error.message; }); document.querySelector('#form').addEventListener('submit', async event => { - event.preventDefault(); connect.disabled = true; disconnect.disabled = true; + event.preventDefault(); + if (connect.disabled) return; + connect.disabled = true; disconnect.disabled = true; status.textContent = text('正在连接…', 'Connecting…'); status.style.color = '#aaa'; try { - const result = await window.connection.pair(server.value, key.value, tailcat.checked); + const result = await window.connection.pair(server.value, key.value, tailcat.checked, canRetry() && !key.value); if (!result.ok) throw new Error(result.error); key.value = ''; status.textContent = text('已连接', 'Connected'); } catch (error) { status.textContent = error.message; status.style.color = '#f09b94'; } finally { connect.disabled = false; disconnect.disabled = false; } }); disconnect.addEventListener('click', async () => { - await window.connection.disconnect(); key.value = ''; disconnect.hidden = true; - connect.textContent = text('连接', 'Connect'); status.textContent = text('已断开', 'Disconnected'); + if (disconnect.disabled) return; + connect.disabled = true; disconnect.disabled = true; + try { + await window.connection.disconnect(); key.value = ''; disconnect.hidden = true; saved = null; updateRetry(); + connect.textContent = text('连接', 'Connect'); status.textContent = text('已断开', 'Disconnected'); + } catch (error) { status.textContent = error.message; status.style.color = '#f09b94'; } + finally { connect.disabled = false; disconnect.disabled = false; } }); diff --git a/mac/clients/desktop/connection.mjs b/mac/clients/desktop/connection.mjs index cf221347cebdd3df13acda4bcb0c4c866d9cca5c..350ca2f705648f2941fa97faf22df8e1ebcc64f5 100644 --- a/mac/clients/desktop/connection.mjs +++ b/mac/clients/desktop/connection.mjs @@ -1,9 +1,16 @@ import { grokText } from './i18n.mjs'; +import { normalizePairingCode } from './pairing-code.mjs'; import { readFile, writeFile, mkdir, rename, rm } from 'node:fs/promises'; import path from 'node:path'; import os from 'node:os'; import { TailcatProcess, tailcatLink } from '../shared/tailcat-process.mjs'; +export function credentialUnavailableText() { + return process.platform === 'darwin' + ? grokText('请解锁 macOS 钥匙串。', 'Unlock your macOS keychain.') + : grokText('系统凭据加密不可用,请确认已登录 Windows 账户。', 'System credential encryption is unavailable. Sign in to your Windows account.'); +} + export async function openTransport(address, enabled, { identity, binary } = {}) { if (!enabled) return { server: normalizeServer(address), address: normalizeServer(address), tailcat: false, close: async () => {} }; address = tailcatLink(address); @@ -15,6 +22,25 @@ export async function openTransport(address, enabled, { identity, binary } = {}) } catch (error) { await tunnel.close(); throw error; } } +export async function restoreConnection(store, binary, open = openTransport) { + let config = null; + try { + config = await store.load(); + if (!config) return { config: null, transport: null, connectionError: '' }; + const transport = await open(config.address ?? config.server, config.tailcat, { identity: config.networkIdentity, binary }); + return { config: { ...config, ...transport }, transport, connectionError: '' }; + } catch { + return { config, transport: null, connectionError: config + ? grokText('无法打开已保存的连接,请重新连接。', 'Could not open the saved connection. Reconnect to try again.') + : grokText('无法读取设备凭证,请重新配对。', 'Could not read device credentials. Pair again.') }; + } +} + +export function finishPairingWindow(opening, current, connectionError) { + // A revocation during workspace startup may reopen the same window to show the error. + if (opening && current === opening && !connectionError) opening.close(); +} + export function normalizeServer(input) { const url = new URL(String(input).trim()); if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || @@ -23,50 +49,80 @@ export function normalizeServer(input) { return url.origin; } +export function savedConnectionMatches(config, address, tunneled) { + if (!config || (config.tailcat === true) !== tunneled) return false; + try { + if (tunneled) return tailcatLink(address) === tailcatLink(config.address); + return normalizeServer(address) === normalizeServer(config.address ?? config.server); + } catch { return false; } +} + +function validDevice(record) { + return typeof record?.deviceId === 'string' && Boolean(record.deviceId.trim()) && + typeof record.token === 'string' && record.token.length >= 16 && !/[^!-~]/.test(record.token); +} + export async function pair(server, pairingKey, fetcher = fetch, { tunneled = false } = {}) { server = normalizeServer(server); - if (!pairingKey?.trim()) throw new Error(grokText('请输入配对码。', 'Enter a pairing code.')); + pairingKey = normalizePairingCode(pairingKey); + if (!/^[A-Z0-9]{6}$/.test(pairingKey)) throw new Error(grokText('请输入 6 位配对码。', 'Enter a six-character pairing code.')); const response = await fetcher(`${server}/connect/pair`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ pairingKey: pairingKey.trim().toUpperCase(), deviceName: os.hostname(), platform: 'desktop' }), + body: JSON.stringify({ pairingKey, deviceName: os.hostname(), platform: 'desktop' }), signal: AbortSignal.timeout(15000), redirect: 'error', }); const result = await response.json().catch(() => ({})); if (!response.ok) throw new Error(response.status === 401 ? grokText('配对码 无效或已过期。', 'Pairing code is invalid or expired.') : grokText(`连接失败(HTTP ${response.status})。`, `Connection failed (HTTP ${response.status}).`)); - if (typeof result.token !== 'string' || result.token.length < 16 || !result.deviceId) + if (!validDevice(result)) throw new Error(grokText('Host 返回的设备凭证无效。', 'Host returned invalid device credentials.')); if (!tunneled && normalizeServer(result.gatewayUrl) !== server) throw new Error(grokText('Host 返回了不同的服务地址。', 'Host returned a different server address.')); return { server, deviceId: result.deviceId, token: result.token }; } +export async function verifyDevice(server, { token, deviceId }, fetcher = fetch) { + const response = await fetcher(`${normalizeServer(server)}/connect/status`, { headers: { authorization: `Bearer ${token}` }, + signal: AbortSignal.timeout(35000), redirect: 'error' }); + if (response.ok) { + const status = await response.json().catch(() => null); + if (typeof deviceId === 'string' && status?.deviceId === deviceId) return; + } else await response.body?.cancel(); + throw new Error(grokText('无法验证此 Host 的设备凭据。', 'Could not verify this device with the Host.')); +} + export function credentialStore(profile, safeStorage) { const filename = path.join(profile, 'connection.json'); + let writes = Promise.resolve(); + const update = task => { writes = writes.catch(() => {}).then(task); return writes; }; function available() { - if (!safeStorage.isEncryptionAvailable()) throw new Error(grokText('请解锁 macOS 钥匙串。', 'Unlock your macOS keychain.')); + if (!safeStorage.isEncryptionAvailable()) throw new Error(credentialUnavailableText()); } return { async load() { + await writes.catch(() => {}); let record; try { record = JSON.parse(await readFile(filename, 'utf8')); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } available(); + const device = { deviceId: record.deviceId, token: safeStorage.decryptString(Buffer.from(record.encryptedToken, 'base64')) }; + if (!validDevice(device)) throw new Error(grokText('保存的设备凭证无效。', 'Saved device credentials are invalid.')); const network = record.encryptedNetwork ? JSON.parse(safeStorage.decryptString(Buffer.from(record.encryptedNetwork, 'base64'))) : null; - return { server: network?.tailcat ? '' : normalizeServer(record.server), deviceId: record.deviceId, + return { ...device, server: network?.tailcat ? '' : normalizeServer(record.server), address: network?.tailcat ? tailcatLink(network.address) : normalizeServer(record.server), - tailcat: network?.tailcat === true, networkIdentity: network?.identity, - token: safeStorage.decryptString(Buffer.from(record.encryptedToken, 'base64')) }; + tailcat: network?.tailcat === true, networkIdentity: network?.identity }; }, - async save(config) { + save: config => update(async () => { available(); await mkdir(profile, { recursive: true, mode: 0o700 }); const record = { version: 1, server: config.tailcat ? '' : normalizeServer(config.address ?? config.server), deviceId: config.deviceId, encryptedToken: safeStorage.encryptString(config.token).toString('base64') }; if (config.tailcat) record.encryptedNetwork = safeStorage.encryptString(JSON.stringify({ tailcat: true, address: tailcatLink(config.address), identity: config.networkIdentity })).toString('base64'); - await writeFile(`${filename}.tmp`, JSON.stringify(record), { mode: 0o600 }); - await rename(`${filename}.tmp`, filename); - }, - async clear() { await rm(filename, { force: true }); }, + try { + await writeFile(`${filename}.tmp`, JSON.stringify(record), { mode: 0o600 }); + await rename(`${filename}.tmp`, filename); + } catch (error) { await rm(`${filename}.tmp`, { force: true }).catch(() => {}); throw error; } + }), + clear: () => update(() => rm(filename, { force: true })), }; } diff --git a/mac/clients/desktop/dictation.mjs b/mac/clients/desktop/dictation.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0b30acc1cf33bf7d0ed37f23edba96de4fb0aa49 --- /dev/null +++ b/mac/clients/desktop/dictation.mjs @@ -0,0 +1,80 @@ +import { grokText } from './i18n.mjs'; + +// Desktop 1.1.0 streams 16 kHz mono PCM16 while the microphone is open and +// waits for the text when recording stops. The Host transcribes whole +// recordings, so each session is buffered here and sent once as a WAV file. +// Plain bytes only: the Android client runs this module in its WebView. +const SAMPLE_RATE = 16000; +const MAX_PCM_BYTES = 25 * 1024 * 1024 - 44; // The Host accepts up to 25 MB per recording. +const TRANSCRIBE_MS = 120000; + +export function pcmWav(pcm, sampleRate = SAMPLE_RATE) { + const wav = new Uint8Array(44 + pcm.length), view = new DataView(wav.buffer); + const ascii = (offset, text) => { for (let i = 0; i < text.length; i++) wav[offset + i] = text.charCodeAt(i); }; + ascii(0, 'RIFF'); view.setUint32(4, 36 + pcm.length, true); ascii(8, 'WAVE'); + ascii(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true); + view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 2, true); + view.setUint16(32, 2, true); view.setUint16(34, 16, true); + ascii(36, 'data'); view.setUint32(40, pcm.length, true); + wav.set(pcm, 44); + return wav; +} + +function base64(bytes) { + let binary = ''; + for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(binary); +} + +function joined(chunks, length) { + const bytes = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + return bytes; +} + +export function createDictation({ request, emit }) { + const sessions = new Map(); + let sequence = 0; + // Like the original desktop, a superseded or cancelled session reports that it ended. + const end = sessionId => { + const session = sessions.get(sessionId); + if (!session) return; + sessions.delete(sessionId); session.abort.abort(); + emit({ sessionId, isEnded: true }); + }; + return { + startDictation: ({ language } = {}) => { + for (const sessionId of [...sessions.keys()]) end(sessionId); + const sessionId = `dictation-${++sequence}`; + sessions.set(sessionId, { language: language || null, chunks: [], bytes: 0, overflow: false, abort: new AbortController() }); + return { sessionId }; + }, + pushDictationAudio: ({ sessionId, pcm16 }) => { + const session = sessions.get(sessionId); + if (!session || session.overflow) return null; + const chunk = (ArrayBuffer.isView(pcm16) ? new Uint8Array(pcm16.buffer, pcm16.byteOffset, pcm16.byteLength) : new Uint8Array(pcm16)).slice(); + if (session.bytes + chunk.length > MAX_PCM_BYTES) { session.overflow = true; return null; } + session.chunks.push(chunk); session.bytes += chunk.length; + return null; + }, + stopDictation: async ({ sessionId }) => { + const session = sessions.get(sessionId); + if (!session) return { text: '' }; + const timer = setTimeout(() => session.abort.abort(new DOMException('Transcription timed out.', 'TimeoutError')), TRANSCRIBE_MS); + try { + if (session.overflow) throw new Error(grokText('录音太长,请分段输入。', 'The recording is too long. Dictate in shorter parts.')); + if (session.bytes === 0) return { text: '' }; + const result = await request('/local/audio/transcriptions', { + audioBase64: base64(pcmWav(joined(session.chunks, session.bytes))), mimeType: 'audio/wav', + ...(session.language ? { language: session.language } : {}), + }, session.abort.signal); + return { text: typeof result?.text === 'string' ? result.text : '' }; + } finally { + clearTimeout(timer); + if (sessions.get(sessionId) === session) sessions.delete(sessionId); + } + }, + cancelDictation: ({ sessionId }) => { end(sessionId); return null; }, + }; +} diff --git a/mac/clients/desktop/gateway.mjs b/mac/clients/desktop/gateway.mjs index 7f0873b13822f8bce43bc6622f07d3e6f5a36522..6942c66ed2c15f143b86defa79f4b4ae173cc9bc 100644 --- a/mac/clients/desktop/gateway.mjs +++ b/mac/clients/desktop/gateway.mjs @@ -1,24 +1,48 @@ import { grokText } from './i18n.mjs'; import { subscribe } from './streams.mjs'; +const COORDINATOR_VERSION = 3; + export function createGateway(config, onUnauthorized, onConnected, onStateChanged) { const lifetime = new AbortController(); const streams = new Set(); let state = 'connecting'; const updateState = value => { if (state !== value) { state = value; onStateChanged?.(value); } }; + const close = () => { lifetime.abort(); updateState('disconnected'); }; + const revoked = () => { if (!lifetime.signal.aborted) { close(); onUnauthorized?.(); } }; + // Connectors and other Host features also answer 401 (an expired OAuth grant, for example), so a + // failed request ends the session only when the Host rejects the device itself. A Host without + // /connect/status gets the original prompt to pair again, without closing the gateway. + let checking; + const deviceStatus = () => checking ??= fetch(`${config.server}/connect/status`, { + headers: { Authorization: `Bearer ${config.token}` }, redirect: 'error', + signal: AbortSignal.any([lifetime.signal, AbortSignal.timeout(15000)]), + }).then(response => { void response.body?.cancel().catch(() => {}); return response.status; }, () => 0) + .finally(() => { checking = undefined; }); + async function unauthorized() { + if (lifetime.signal.aborted) return; + const status = await deviceStatus(); + if (lifetime.signal.aborted) return; + if (status === 401) revoked(); + else if (status === 404) onUnauthorized?.(); + } async function request(endpoint, args, signal, method = 'POST') { if (lifetime.signal.aborted) throw new Error(grokText('已退出连接,请重新连接。', 'Disconnected. Connect again.')); + const active = signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal; const response = await fetch(`${config.server}${endpoint}`, { method, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.token}` }, ...(method === 'GET' ? {} : { body: JSON.stringify(args) }), - signal: signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal, redirect: 'error', + signal: active, redirect: 'error', }); - if (response.status === 401) onUnauthorized(); - const value = await response.json(); + active.throwIfAborted(); // A late 401 for a closed port is not a revocation of its live siblings. if (process.env.GROKBOT_LOCAL_DEBUG_PORT) console.log('[gateway]', endpoint, response.status); - if (!response.ok) throw Object.assign(new Error(value?.message ?? value?.error ?? `HTTP ${response.status}`), - { httpStatus: response.status, failureCode: value?.failureCode }); - return value; + if (!response.ok) { + if (response.status === 401) await unauthorized(); + const value = await response.json().catch(() => null); + throw Object.assign(new Error(value?.message ?? value?.error ?? `HTTP ${response.status}`), + { httpStatus: response.status, failureCode: value?.failureCode }); + } + return response.status === 204 || response.status === 205 ? null : await response.json(); } async function command(method, args = {}, signal) { if (lifetime.signal.aborted) throw new Error(grokText('已退出连接,请重新连接。', 'Disconnected. Connect again.')); @@ -27,48 +51,81 @@ export function createGateway(config, onUnauthorized, onConnected, onStateChange if (method === 'resolveAgentCreation') return { kind: 'box' }; if (method === 'restoreTemporalAgentRouting' || method === 'noteMountedAgent') return null; if (method === 'createAgent') { const { creationRoute, ...rest } = args; args = rest; } + // Desktop 1.1.0 renamed global search and pages older results; the Host answers in one page. + if (method === 'searchMessages' || method === 'searchFiles') { + const matches = await request(`/api/${method === 'searchMessages' ? 'searchAgents' : 'searchMedia'}`, { query: args.query }, signal); + return { matches, coverage: { kind: 'complete' } }; + } + // The Host keeps no read receipts for transcripts and has no pending lessons to offer. + if (method === 'noteTranscriptOpened') return null; + if (method === 'takeTeachLearningPrompts') return []; return request(`/api/${encodeURIComponent(method)}`, args, signal); } function attach(port) { const controller = new AbortController(); if (lifetime.signal.aborted) { port.close(); return () => {}; } let subscribed = false, generation = 0; + const pending = new Map(); const send = frame => { if (!controller.signal.aborted) port.postMessage(frame); }; const emit = (family, payload) => send({ kind: 'event', family, payload }); const receive = async ({ data: frame }) => { if (!frame || controller.signal.aborted) return; if (frame.kind === 'lifecycle' && frame.phase === 'hello') { - send({ kind: 'lifecycle', phase: 'ready', protocolVersion: 3 }); - if (!subscribed) { - subscribed = true; - void subscribe(config, '/events', ({ data }) => { - if (data.channel) emit(data.channel, data.payload); - }, controller.signal, { - onConnected: () => { streams.add(controller); updateState('online'); emit('transport-connected', { generation: ++generation }); onConnected?.(); }, - onDisconnected: () => { streams.delete(controller); if (!streams.size) updateState('reconnecting'); emit('transport-down', { generation, reason: 'stream-error', cause: null }); }, - onUnauthorized, - }); + // The legacy hello can omit a version. Never acknowledge a different explicit wire version. + if (Object.hasOwn(frame, 'protocolVersion') && frame.protocolVersion !== COORDINATOR_VERSION) { dispose(); return; } + // A second ready is a protocol error for a live renderer session. + if (subscribed) return; + subscribed = true; + send({ kind: 'lifecycle', phase: 'ready', protocolVersion: COORDINATOR_VERSION }); + void subscribe(config, '/events', ({ data }) => { + if (data.channel) emit(data.channel, data.payload); + }, controller.signal, { + onConnected: () => { + streams.add(controller); updateState('online'); + emit('coordinator-transport-state', { state: 'connected' }); + emit('transport-connected', { generation: ++generation }); onConnected?.(); + }, + onDisconnected: () => { + streams.delete(controller); if (!streams.size) updateState('reconnecting'); + emit('coordinator-transport-state', { state: 'down' }); + emit('transport-down', { generation, reason: 'stream-error', cause: null }); + }, + // The event stream answers 401 only for the device credential. + onUnauthorized: revoked, + }); + } else if (frame.kind === 'lifecycle' && frame.phase === 'shutdown') { + dispose(); + } else if (frame.kind === 'cancel') { + pending.get(frame.requestId)?.abort(); + } else if (frame.kind === 'request' && !pending.has(frame.requestId)) { + const call = new AbortController(); + pending.set(frame.requestId, call); + try { + const value = await command(frame.method, frame.args, call.signal); + call.signal.throwIfAborted(); + send({ kind: 'reply', requestId: frame.requestId, outcome: { status: 'ok', value } }); } - } else if (frame.kind === 'request') { - try { send({ kind: 'reply', requestId: frame.requestId, - outcome: { status: 'ok', value: await command(frame.method, frame.args, controller.signal) } }); } catch (error) { send({ kind: 'reply', requestId: frame.requestId, outcome: { status: 'failed', failure: { - code: 'gateway-command-failed', message: error.message, + code: call.signal.aborted ? 'cancelled' : 'gateway-command-failed', message: error.message, ...(error.httpStatus ? { httpStatus: error.httpStatus } : {}), ...(error.failureCode ? { failureCode: error.failureCode } : {}), } } }); } + finally { pending.delete(frame.requestId); } } }; const cleanup = () => { + if (controller.signal.aborted) return; controller.abort(); streams.delete(controller); - lifetime.signal.removeEventListener('abort', cleanup); + for (const call of pending.values()) call.abort(); + pending.clear(); + lifetime.signal.removeEventListener('abort', dispose); port.off('message', receive); port.off('close', cleanup); if (!streams.size && !lifetime.signal.aborted) updateState('reconnecting'); }; - lifetime.signal.addEventListener('abort', cleanup, { once: true }); + const dispose = () => { if (!controller.signal.aborted) { cleanup(); port.close(); } }; + lifetime.signal.addEventListener('abort', dispose, { once: true }); port.on('message', receive); port.on('close', cleanup); port.start(); - return () => { cleanup(); port.close(); }; + return dispose; } - return { command, request, attach, getState: () => state, - close: () => { lifetime.abort(); updateState('disconnected'); } }; + return { command, request, attach, getState: () => state, close }; } diff --git a/mac/clients/desktop/local-exec.mjs b/mac/clients/desktop/local-exec.mjs index bac3c8fdba96520e2bb15c951f2e05aadb2ea25e..54658860ac648f2d68fe15c1d40888a132e90091 100644 --- a/mac/clients/desktop/local-exec.mjs +++ b/mac/clients/desktop/local-exec.mjs @@ -1,5 +1,6 @@ import { grokText } from './i18n.mjs'; -import { createRequire } from 'node:module'; +import Module, { createRequire } from 'node:module'; +import { readFileSync } from 'node:fs'; import { readFile, writeFile, rename, mkdir, rm } from 'node:fs/promises'; import path from 'node:path'; import os from 'node:os'; @@ -7,8 +8,28 @@ import { createNativeComputer } from './native-computer.mjs'; import { startNativeProvider } from './native-provider.mjs'; import { createCodexBridge } from './codex-bridge.mjs'; +// The 0.71.2 Windows daemon runs commands in Windows PowerShell without its own UTF-8 console +// option, so output in the OEM code page (for example Chinese text) is decoded as UTF-8 and garbled. +// 1.1.0 turns the option on in the daemon itself. +const UTF8_CONSOLE = { from: 'new e3(i,t,t,void 0,void 0,void 0,s)', to: 'new e3(i,t,t,void 0,void 0,!0 ,s)' }; +const UTF8_BUILT_IN = '{keepBackgroundJobs:!0,powershellUtf8Console:!0,powershellUtf8ChildEnv:!0}'; +export function loadLocalExecDaemon(file, platform = process.platform) { + if (platform !== 'win32') return createRequire(import.meta.url)(file); + const source = readFileSync(file, 'utf8'); + if (source.includes(UTF8_BUILT_IN)) return createRequire(import.meta.url)(file); + if (!source.includes(UTF8_CONSOLE.from)) { + console.warn('[local-exec] UTF-8 console option not found; command output keeps the system code page'); + return createRequire(import.meta.url)(file); + } + const daemon = new Module(file); + daemon.filename = file; + daemon.paths = Module._nodeModulePaths(path.dirname(file)); + daemon._compile(source.replace(UTF8_CONSOLE.from, UTF8_CONSOLE.to), file); + return daemon.exports; +} + export async function createLocalExec({ payload, profile, config, command, window }) { - const original = createRequire(import.meta.url)(path.join(payload, 'local-exec-daemon/main.cjs')); + const original = loadLocalExecDaemon(path.join(payload, 'local-exec-daemon/main.cjs')); const directory = path.join(profile, 'local-exec'); await mkdir(directory, { recursive: true, mode: 0o700 }); const root = path.join(directory, 'workspace'); @@ -18,7 +39,8 @@ export async function createLocalExec({ payload, profile, config, command, windo const retirementsPath = path.join(directory, 'retirements.json'); const standingGrantsPath = path.join(directory, 'standing-grants.json'); let native, codex, closed = false; - const machineId = `mac-${config.deviceId}`; + // The Host derives the platform from this prefix; macOS keeps its original form. + const machineId = `${process.platform === 'win32' ? 'win' : 'mac'}-${config.deviceId}`; let permission = 'ask', writes = Promise.resolve(); try { const value = JSON.parse(await readFile(settingsPath, 'utf8')); if (['ask', 'never', 'always'].includes(value.permission)) permission = value.permission; } catch {} const serialize = task => { writes = writes.catch(() => {}).then(task); return writes; }; @@ -76,7 +98,7 @@ export async function createLocalExec({ payload, profile, config, command, windo await save(approvalsPath, { approvals: [...entries.filter(item => item.id !== record.id), record].slice(-500) }); }), clearLocalToolApprovals: () => serialize(async () => { await rm(approvalsPath, { force: true }); await rm(retirementsPath, { force: true }); }), - getSandMachines: () => ({ machines: [{ machineId, name: os.hostname(), label: os.hostname(), platform: 'darwin', + getSandMachines: () => ({ machines: [{ machineId, name: os.hostname(), label: os.hostname(), platform: process.platform, isCurrent: true, localToolPermission: permission, isOnline: Boolean(provider.providerId) }], currentMachineRemoved: false }), getLocalExecutionStatus: () => ({ connected: Boolean(provider.providerId), machineId, root, permission }), }, diff --git a/mac/clients/desktop/local-services.mjs b/mac/clients/desktop/local-services.mjs index c1bcd3ce79ec48ae2e208dc99f0e972140e3cbbc..901e6e454ba408b42d6ca3a20196c2784e040c2e 100644 --- a/mac/clients/desktop/local-services.mjs +++ b/mac/clients/desktop/local-services.mjs @@ -2,8 +2,8 @@ import { grokText } from './i18n.mjs'; import { createConnectorHandlers } from './connectors.mjs'; import { externalHttpUrl } from './external-url.mjs'; import { createLinkPreview } from './link-preview.mjs'; -import { readFile, writeFile } from "node:fs/promises"; -import path from "node:path"; +import { createClientPersistence } from './client-persistence.mjs'; +import { createDictation } from './dictation.mjs'; export const auth = { kind: "logged-in", authId: "grokbot-local-workspace", @@ -53,22 +53,46 @@ const access = { proAndSuperGrokPlansGrantAccess: false, isUnified: false, }; -export async function createLocalServices(profile, window, { command, request, attachment, attachmentHandlers = {}, connection, disconnect, notifications, pickAvatarFile, openExternal, settings = {} }) { - const storePath = path.join(profile, "local-client-persistence.json"); - let store = {}; - try { - store = JSON.parse(await readFile(storePath, "utf8")); - } catch {} - const persist = () => writeFile(storePath, JSON.stringify(store), "utf8"); +export function probeLocalMethod(trusted, declared, call, method) { + return { ok: Boolean(trusted), value: Boolean(trusted && declared.has(method) && call?.supports(method)) }; +} + +/** + * Methods of each RPC edge in the official preload. The minified declaration + * helper is renamed per build (`t()` in 0.71.2, `n()` in 1.1.0). Edges other + * than `main` declare their methods inline; `main` keeps everything else. + */ +export function desktopEdges(preload) { + const declared = source => [...source.matchAll(/([A-Za-z_$][\w$]*):[A-Za-z_$][\w$]*\(\)\.(?:args|noArgs)/g)].map(match => match[1]); + const counts = new Map(); + for (const name of declared(preload)) counts.set(name, (counts.get(name) ?? 0) + 1); + const others = new Map(); + for (const match of preload.matchAll(/\("([a-z][a-z-]*)",\{methods:\{/g)) { + if (match[1] === 'main') continue; + let end = match.index + match[0].length - 1; + for (let depth = 0; end < preload.length; end++) { + if (preload[end] === '{') depth++; + else if (preload[end] === '}' && --depth === 0) break; + } + const names = declared(preload.slice(match.index, end)); + others.set(match[1], new Set(names)); + for (const name of names) counts.set(name, counts.get(name) - 1); + } + return { main: new Set([...counts].filter(([, count]) => count > 0).map(([name]) => name)), others }; +} + +export async function createLocalServices(profile, window, { command, request, attachment, attachmentHandlers = {}, connection, disconnect, notifications, pickAvatarFile, openExternal, settings = {}, appVersion, persistence = createClientPersistence(profile), emit = () => {} }) { const linkPreview = createLinkPreview({ profile }); const known = { getLinkMetadata: args => linkPreview.getMetadata(args), resolveAttachmentMedia: attachment, ...attachmentHandlers, + // 0.71.2 sends a finished recording; 1.1.0 streams it through the dictation methods. transcribeAudio: ({ audio, mimeType, language }) => request('/local/audio/transcriptions', { audioBase64: Buffer.from(audio).toString('base64'), mimeType, ...(language ? { language } : {}), }, AbortSignal.timeout(120000)), + ...createDictation({ request, emit: value => emit('dictation-text', value) }), openSelfHostedConnection: connection, loginCursor: connection, logoutCursor: disconnect, @@ -78,6 +102,9 @@ export async function createLocalServices(profile, window, { command, request, a uploadGrokBotAgentFile: ({ agentId, fileName, contentType, bytes }) => request('/local/files', { agentId, fileName, contentType, base64: Buffer.from(bytes).toString('base64') }, AbortSignal.timeout(60000)), deleteGrokBotAgentFile: async ({ agentId, name }) => { await request('/local/files', { agentId, name }, AbortSignal.timeout(15000), 'DELETE'); }, + // 1.1.0 also lists files a cloud Bot keeps per user; Host Bots keep only their library. + listGrokBotUserStoreFiles: () => ({ files: [] }), + deleteGrokBotUserStoreFile: () => null, getAutoReviewInstructions: async () => (await command('getHostSettings')).autoReviewInstructions ?? { isEnabled: false, allowInstructions: [], blockInstructions: [] }, setAutoReviewInstructions: async ({ instructions }) => { await command('setHostSettings', { autoReviewInstructions: instructions }); @@ -136,35 +163,16 @@ export async function createLocalServices(profile, window, { command, request, a isFullScreen: window.isFullScreen(), isFocused: window.isFocused(), }), + isWindowShown: () => window.isVisible() && !window.isMinimized(), minimizeWindow: () => window.minimize(), focusWindow: () => window.focus(), closeWindow: () => window.close(), toggleMaximizeWindow: () => window.isMaximized() ? window.unmaximize() : window.maximize(), - readClientPersistence: ({ key }) => store[key] ?? null, - readManyClientPersistence: ({ include, exclude = [] }) => - Object.fromEntries(Object.entries(store).filter(([key]) => { - const longest = prefixes => prefixes.reduce((length, prefix) => - key.startsWith(prefix) ? Math.max(length, prefix.length) : length, -1); - const included = longest(include); - return included >= 0 && included >= longest(exclude); - })), - writeClientPersistence: async ({ key, value }) => { - store[key] = value; - await persist(); - }, - removeClientPersistence: async ({ key }) => { - delete store[key]; - await persist(); - }, - listClientPersistenceKeys: ({ prefix }) => - Object.keys(store).filter((x) => x.startsWith(prefix)), - hasMigratedClientPersistence: () => true, - migrateClientPersistence: async ({ entries }) => { - for (const e of entries) store[e.key] = e.value; - await persist(); - }, + ...persistence, getEgressTunnelEnabled: () => false, + getEgressTunnelForcedByAdmin: () => false, + claimEgressTunnel: () => null, getWebauthnProxyEnabled: () => true, getBotColorInChatEnabled: () => false, getEgressTunnelStatus: () => boot.egressTunnelStatus, @@ -172,7 +180,7 @@ export async function createLocalServices(profile, window, { command, request, a getHardwareAcceleration: () => true, getUpdateStatus: () => ({ state: { type: "disabled", reason: "disabled-by-env" }, - currentVersion: "0.71.2", + currentVersion: appVersion, currentTrack: "stable", availableTracks: ["stable"], isTrackManagedByPolicy: true, @@ -187,7 +195,15 @@ export async function createLocalServices(profile, window, { command, request, a }), ...createConnectorHandlers({ command, openExternal }), getCursorPrivacyModeEnabled: () => false, + getCursorStorageAllowed: () => false, getCursorUnifyCta: () => null, + // The original signed-out answers: nothing is offered and nothing is sent to a cloud account. + getCursorTrainingOptIn: () => "unavailable", + getCursorTrainingSetting: () => "signed-out", + getCursorBonfireStatus: () => ({ kind: "ineligible" }), + getLocalPitmanState: () => ({ isRecorderReady: false, session: null }), + getPendingRestartToUpdate: () => null, + getMicrosoftTeamsAccountLinkStatus: () => ({ links: [], teamEnablement: null }), getCurrentMachineMessagesEnabled: () => false, listSecrets: () => [], listMeetings: () => [], @@ -208,8 +224,9 @@ export async function createLocalServices(profile, window, { command, request, a setHostSettings: (args) => command("setHostSettings", args), }; Object.assign(known, settings); - return async (method, args = {}) => { - if (known[method]) return known[method](args); + const supports = method => typeof method === 'string' && Object.hasOwn(known, method) && typeof known[method] === 'function'; + const call = async (method, args = {}) => { + if (supports(method)) return known[method](args); if ( /^(report|note|expose|log|setTitleBar|setUnreadFilter|setWindow|markGrokBotTerms)/.test( method, @@ -219,4 +236,6 @@ export async function createLocalServices(profile, window, { command, request, a console.error("[missing local method]", method); throw new Error(`Local desktop does not implement ${method}`); }; + // Passive compatibility notices above are not implemented capabilities. + return Object.assign(call, { supports }); } diff --git a/mac/clients/desktop/main.mjs b/mac/clients/desktop/main.mjs index 087a93874aa3edd97b8b60bfa937e5fa9565e822..7c4fa515109d626924d76851830194f871ffac9e 100644 --- a/mac/clients/desktop/main.mjs +++ b/mac/clients/desktop/main.mjs @@ -1,10 +1,13 @@ -import { app, BrowserWindow, clipboard, dialog, ipcMain, MessageChannelMain, Menu, nativeImage, nativeTheme, Notification, safeStorage, session, shell } from 'electron'; +import { app, BrowserWindow, clipboard, dialog, ipcMain, MessageChannelMain, Menu, nativeImage, nativeTheme, Notification, safeStorage, screen, session, shell, Tray } from 'electron'; import { readFile, mkdir } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { grokText as localText, setLocaleSource } from './i18n.mjs'; -import { credentialStore, pair, openTransport } from './connection.mjs'; +import { credentialStore, credentialUnavailableText, finishPairingWindow, pair, verifyDevice, openTransport, restoreConnection, savedConnectionMatches } from './connection.mjs'; +import { APP_USER_MODEL_ID, canRegisterDesktopIntegration, connectWindowChrome, createTray, ensureStartMenuShortcut, initialLink, isWindows, + windowChrome, windowHandlers } from './platform.mjs'; import { createGateway } from './gateway.mjs'; +import { createClientPersistence } from './client-persistence.mjs'; import { createAttachmentHandlers, createAttachmentMediaResolver } from './attachments.mjs'; import { createAttachmentUploads } from './attachment-uploads.mjs'; import { createNotifications, agentFromLink } from './notifications.mjs'; @@ -16,15 +19,18 @@ import { createSounds } from './sounds.mjs'; import { mintVoiceCredential, createVoiceAvailability } from './voice.mjs'; import { externalHttpUrl } from './external-url.mjs'; import { installExternalLinks } from './external-links.mjs'; -import { auth, boot, theme, language, experiments, createLocalServices } from './local-services.mjs'; +import { auth, boot, theme, language, experiments, createLocalServices, desktopEdges, probeLocalMethod } from './local-services.mjs'; const clientRoot = path.dirname(fileURLToPath(import.meta.url)); const payload = path.join(clientRoot, '../dist'); -const profile = process.env.GROKBOT_LOCAL_DEBUG_PORT && process.env.GROKBOT_LOCAL_TEST_PROFILE +const isolatedProfile = Boolean(process.env.GROKBOT_LOCAL_DEBUG_PORT && process.env.GROKBOT_LOCAL_TEST_PROFILE); +const profile = isolatedProfile ? path.resolve(process.env.GROKBOT_LOCAL_TEST_PROFILE) : path.join(app.getPath('appData'), 'Grok Bot Local'); app.setPath('userData', profile); app.setName('Grok Bot Local'); +// Windows groups windows and delivers toasts by this ID; it matches the Start menu shortcut. +if (isWindows) app.setAppUserModelId(APP_USER_MODEL_ID); const clientSettings = loadSettings(profile); const enabledAtLaunch = clientSettings.hardwareAcceleration; if (!enabledAtLaunch) app.disableHardwareAcceleration(); @@ -38,26 +44,40 @@ if (process.env.GROKBOT_LOCAL_DEBUG_PORT) { } let config, mainWindow, connectWindow, gateway, notifications, connectionError = ''; let quitting = false, starting = true; -let transport; -const transportBinary = path.join(process.resourcesPath, 'grokbot-tailcat'); +let transport, tray; +const transportBinary = path.join(process.resourcesPath, isWindows ? 'grokbot-tailcat.exe' : 'grokbot-tailcat'); let methodCall, accountProfile, localExec, browserProviders, voiceAvailability, deepLinksReady = false, pendingAgent = null; const ports = new Set(); const store = credentialStore(profile, safeStorage); +const persistence = createClientPersistence(profile); if (!app.requestSingleInstanceLock()) app.exit(0); app.on('second-instance', (_event, argv) => { const link = argv.find(value => value.startsWith('grokbot-local:')); if (link) routeLink(link); - (mainWindow ?? connectWindow)?.show(); + else void showApp(); }); app.on('open-url', (event, url) => { event.preventDefault(); routeLink(url); }); -// Re-pairing replaces the workspace window. Keep the macOS process alive during -// that transition, just as closing the regular window keeps the client running. +// Re-pairing replaces the workspace window. Keep the process alive during that +// transition, just as closing the regular window keeps the client running +// (in the menu bar on macOS, in the notification area on Windows). app.on('window-all-closed', () => {}); +/** Bring back the current window, as the Dock icon does on macOS. */ +async function showApp() { + if (!app.isReady()) return; + const window = mainWindow && !mainWindow.isDestroyed() ? mainWindow : connectWindow; + if (window && !window.isDestroyed()) { + // Windows may bring a hidden window back iconic when the call comes from the background. + window.show(); + if (window.isMinimized()) window.restore(); + window.focus(); return; + } + if (!starting) await (transport && config ? showWorkspace() : showConnection()); +} function routeLink(url) { const id = agentFromLink(url); if (id) openAgent(id); } function openAgent(id) { pendingAgent = id; if (!mainWindow || mainWindow.isDestroyed()) { - if (config && app.isReady()) void showWorkspace(); + if (transport && config && app.isReady()) void showWorkspace(); return; } if (mainWindow.isMinimized()) mainWindow.restore(); @@ -88,9 +108,9 @@ function disposeWorkspace() { mainWindow = null; } function connectionStatus() { - return { paired: Boolean(config), connected: Boolean(config), server: config?.address ?? config?.server, + return { paired: Boolean(config), connected: Boolean(transport && config), server: config?.address ?? config?.server, tailcat: config?.tailcat === true, transportPath: transport?.tunnel?.status.path ?? 'direct', - state: config ? gateway?.getState() ?? 'connecting' : 'disconnected', + state: transport && config ? gateway?.getState() ?? 'connecting' : 'disconnected', profile: config ? accountProfile?.current() ?? null : null, error: connectionError }; } function reportConnection() { @@ -109,9 +129,8 @@ async function openExternal(value) { async function showConnection() { if (!app.isReady()) return; if (connectWindow && !connectWindow.isDestroyed()) { connectWindow.show(); connectWindow.focus(); return; } - connectWindow = new BrowserWindow({ width: 510, height: 510, resizable: false, - title: localText('连接 Grok Bot', 'Connect Grok Bot'), backgroundColor: '#111111', titleBarStyle: 'hiddenInset', - trafficLightPosition: { x: 16, y: 15 }, + connectWindow = new BrowserWindow({ width: 510, height: 510, resizable: false, maximizable: false, + title: localText('连接 Grok Bot', 'Connect Grok Bot'), backgroundColor: '#111111', ...connectWindowChrome(), webPreferences: { preload: path.join(clientRoot, 'connect-preload.cjs'), sandbox: true, nodeIntegration: false, contextIsolation: true } }); connectWindow.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); connectWindow.webContents.on('will-navigate', event => event.preventDefault()); @@ -119,13 +138,15 @@ async function showConnection() { await connectWindow.loadFile(path.join(clientRoot, 'connect.html')); } function updateMenu() { - Menu.setApplicationMenu(Menu.buildFromTemplate([ - { label: 'Grok Bot', submenu: [{ role: 'about' }, { type: 'separator' }, + // Windows windows are frameless with native caption buttons; the menu only supplies shortcuts. + Menu.setApplicationMenu(Menu.buildFromTemplate(isWindows + ? [{ role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }] + : [{ label: 'Grok Bot', submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'hide' }, { role: 'hideOthers' }, { role: 'unhide' }, { type: 'separator' }, { role: 'quit' }] }, - { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }, - ])); + { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }])); } async function showWorkspace() { + const pairingWindow = connectWindow; disposeWorkspace(); const activeConfig = config; const reportFocus = () => { @@ -133,12 +154,18 @@ async function showWorkspace() { if (mainWindow?.isFocused()) void accountProfile?.refresh().catch(() => {}); }; gateway = createGateway(activeConfig, unauthorized, reportFocus, reportConnection); + // The Host lists unnamed desktop clients as Macs; Windows reports itself once per session. + if (isWindows) void gateway.request('/local/device', { kind: 'desktop', clientKind: 'windows', appVersion: app.getVersion() }, + AbortSignal.timeout(15000), 'PUT').catch(() => {}); + // Apply the saved theme (dark by default) before the first paint; createSettings applies it again. + if (['dark', 'light', 'system'].includes(clientSettings.theme)) nativeTheme.themeSource = clientSettings.theme; + const background = nativeTheme.shouldUseDarkColors ? '#111111' : '#ffffff'; const win = new BrowserWindow({ width: 1200, height: 850, minWidth: 720, minHeight: 500, - title: 'Grok Bot', backgroundColor: '#111111', frame: true, titleBarStyle: 'hiddenInset', - trafficLightPosition: { x: 16, y: 15 }, + title: 'Grok Bot', backgroundColor: background, ...windowChrome(background), webPreferences: { preload: path.join(clientRoot, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: false, webviewTag: true } }); mainWindow = win; + const chrome = windowHandlers(win, background, { workArea: window => screen.getDisplayMatching(window.getBounds()).workArea }); voiceAvailability = createVoiceAvailability({ request: gateway.request, window: win, experiments, getPreference: () => clientSettings.realtimeVoice }); void voiceAvailability.refresh(); accountProfile = createProfile({ request: gateway.request, window: win, auth, server: activeConfig.server, onChange: reportConnection }); @@ -147,6 +174,11 @@ async function showWorkspace() { browserProviders = await createBrowserProviders({ payload, profile, config: activeConfig, window: win, BrowserWindow, locale: () => language.resolved }); win.on('focus', reportFocus); win.on('blur', reportFocus); + // 1.1.0 tracks whether the workspace is on screen; 0.71.2 ignores these events. + const send = (name, value) => { if (!win.isDestroyed()) win.webContents.send(`dune-rpc:main:e:${name}`, value); }; + for (const event of ['show', 'hide', 'minimize', 'restore']) + win.on(event, () => send('window-visibility', { visible: win.isVisible() && !win.isMinimized() })); + win.on('focus', () => send('window-focus', {})); win.on('close', event => { if (!quitting) { event.preventDefault(); win.hide(); } if (process.env.GROKBOT_LOCAL_DEBUG_PORT) console.log('[notification-window]', JSON.stringify({visible:win.isVisible(),focused:win.isFocused(),quitting})); @@ -159,10 +191,11 @@ async function showWorkspace() { const uploads = createAttachmentUploads({ profile, command: gateway.command, onProgress: progress => { if (!win.isDestroyed()) win.webContents.send('dune-rpc:main:e:attachment-commit-progress', progress); } }); methodCall = await createLocalServices(profile, win, { + appVersion: app.getVersion(), persistence, emit: send, command: gateway.command, request: gateway.request, connection: showConnection, openExternal, attachmentHandlers: { ...uploads.handlers, ...createAttachmentHandlers({ command: gateway.command, - readStaged: uploads.readStaged, + withStaged: uploads.withStaged, chooseDestination: async name => { const result = await dialog.showSaveDialog(win, { defaultPath: path.join(app.getPath('downloads'), name) }); return result.canceled ? null : result.filePath; @@ -171,7 +204,9 @@ async function showWorkspace() { message: localText('无法下载文件,请重试。', 'Could not download this file. Try again.') }), }) }, disconnect: async () => { await store.clear(); config = null; disposeWorkspace(); await transport?.close(); transport = null; await showConnection(); }, notifications, - settings: { ...createSettings({ profile, window: win, app, nativeTheme, settings: clientSettings, enabledAtLaunch, command: gateway.command, theme, language, boot, onVoicePreference: () => voiceAvailability.refresh() }), ...accountProfile.handlers, ...localExec.handlers, ...browserProviders.handlers, + settings: { ...createSettings({ profile, window: win, app, nativeTheme, settings: clientSettings, enabledAtLaunch, command: gateway.command, theme, language, boot, + onVoicePreference: () => voiceAvailability.refresh(), onBackground: chrome.setBackground }), ...chrome.handlers, + ...accountProfile.handlers, ...localExec.handlers, ...browserProviders.handlers, getExperimentsSnapshot: () => voiceAvailability.refresh() }, pickAvatarFile: async () => { const result = await dialog.showOpenDialog(win, { properties: ['openFile'], filters: [{ name: localText('图片', 'Images'), extensions: ['png', 'jpg', 'jpeg', 'webp'] }] }); @@ -182,7 +217,7 @@ async function showWorkspace() { if (image.isEmpty()) throw new Error(localText('无法读取图片。', 'Could not read this image.')); return { dataUrl: image.toDataURL(), fileName: path.basename(result.filePaths[0]) }; }, - attachment: createAttachmentMediaResolver({ command: gateway.command, readStaged: uploads.readStaged, nativeImage }), + attachment: createAttachmentMediaResolver({ command: gateway.command, withStaged: uploads.withStaged, nativeImage }), }); installExternalLinks(win, { openExternal, clipboard, Menu, text: localText }); win.webContents.on('will-attach-webview', (event, preferences, params) => { @@ -201,9 +236,13 @@ async function showWorkspace() { }); win.webContents.on('preload-error', (_event, _file, error) => console.error('[preload]', error.message)); win.webContents.on('render-process-gone', (_event, details) => console.error('[renderer]', details.reason)); + const workspaceStyle = await readFile(path.join(clientRoot, 'workspace.css'), 'utf8'); + win.webContents.on('did-finish-load', () => { + void win.webContents.insertCSS(workspaceStyle).catch(error => console.error('[workspace-style]', error.message)); + }); await win.loadFile(path.join(payload, 'renderer/index.html')); updateMenu(); - connectWindow?.close(); + finishPairingWindow(pairingWindow, connectWindow, connectionError); } ipcMain.on('grokbot-local:locale', event => { event.returnValue = trusted(event, mainWindow) || trusted(event, connectWindow) ? (clientSettings.language === 'system' ? app.getLocale() : clientSettings.language) : 'en'; }); @@ -219,7 +258,8 @@ ipcMain.handle('grokbot-local:voice-credential', async (event, agentId) => { if (clientSettings.realtimeVoice !== true) throw new Error(localText('请启用实时语音。', 'Enable realtime voice.')); return { ok: true, credential: await mintVoiceCredential({ request: gateway.request, server: config.server }, agentId) }; } - catch (error) { return { ok: false, fault: 'unavailable', detail: error.message }; } + // 1.1.0 reads a missing usage refusal as a usage limit; this failure is never one. + catch (error) { return { ok: false, fault: { reason: 'unavailable' }, usageRefusal: null, detail: error.message }; } }); ipcMain.handle('grokbot-local:voice-preference', async (event, enabled) => { if (!trusted(event, mainWindow) || !methodCall) throw new Error('Unexpected renderer'); @@ -228,21 +268,26 @@ ipcMain.handle('grokbot-local:voice-preference', async (event, enabled) => { ipcMain.handle('grokbot-local:pair', async (event, args) => { requireConnection(event); try { + const saved = config, editing = args.edit === true, tunneled = args.tailcat === true; + if (editing && !savedConnectionMatches(saved, args.server, tunneled)) + throw new Error(localText('更改 Host 地址需要新的配对码。', 'Enter a new pairing code to change the Host address.')); // Check the keychain before consuming a one-use pairing Key. - if (!safeStorage.isEncryptionAvailable()) throw new Error(localText('请解锁 macOS 钥匙串。', 'Unlock your macOS keychain.')); - const nextTransport = await openTransport(args.server, args.tailcat === true, { binary: transportBinary }); + if (!safeStorage.isEncryptionAvailable()) throw new Error(credentialUnavailableText()); + const reuse = editing && tunneled && transport?.tunnel?.status.state === 'ready'; + const nextTransport = reuse ? transport : await openTransport(args.server, tunneled, + { binary: transportBinary, identity: editing && tunneled ? saved.networkIdentity : undefined }); let next; try { - if (args.edit === true) { - if (!config) throw new Error('Not connected'); - const response = await fetch(`${nextTransport.server}/connect/status`, { headers: { authorization: `Bearer ${config.token}` }, signal: AbortSignal.timeout(35000), redirect: 'error' }); - if (!response.ok) throw new Error(localText('无法验证此 Host 的设备凭据。', 'Could not verify this device with the Host.')); - await response.body?.cancel(); next = { ...config, ...nextTransport }; + if (editing) { + if (config !== saved) throw new Error(localText('连接已更改,请重试。', 'Connection changed. Try again.')); + await verifyDevice(nextTransport.server, saved); + if (config !== saved) throw new Error(localText('连接已更改,请重试。', 'Connection changed. Try again.')); + next = { ...saved, ...nextTransport }; } else next = { ...await pair(nextTransport.server, args.key, fetch, { tunneled: nextTransport.tailcat }), ...nextTransport }; await store.save(next); - } catch (error) { await nextTransport.close(); throw error; } - disposeWorkspace(); await transport?.close(); transport = nextTransport; config = next; connectionError = ''; - setTimeout(() => { void showWorkspace(); }, 200); + } catch (error) { if (!reuse) await nextTransport.close(); throw error; } + disposeWorkspace(); if (!reuse) await transport?.close(); transport = nextTransport; config = next; connectionError = ''; + setTimeout(() => { if (config === next && !quitting) void showWorkspace(); }, 200); return { ok: true }; } catch (error) { return { ok: false, error: error.message }; } }); @@ -274,7 +319,8 @@ ipcMain.handle('sand:coordinator-port-request', event => { app.whenReady().then(async () => { setLocaleSource(() => clientSettings.language === 'system' ? app.getLocale() : clientSettings.language); await mkdir(profile, { recursive: true, mode: 0o700 }); -app.setAsDefaultProtocolClient('grokbot-local'); +const registerIntegration = await canRegisterDesktopIntegration({ isolatedProfile }); +if (registerIntegration && (!isWindows || !app.getApplicationNameForProtocol('grokbot-local://'))) app.setAsDefaultProtocolClient('grokbot-local'); // Official update and account network code is never started. Renderer traffic // is restricted to the current Host; credentials stay in this main process. const restrict = target => target.webRequest.onBeforeRequest((details, callback) => { @@ -286,8 +332,13 @@ const restrict = target => target.webRequest.onBeforeRequest((details, callback) } catch { callback({ cancel: true }); } }); restrict(session.defaultSession); app.on('session-created', restrict); -const preload = await readFile(path.join(payload, 'electron-preload/preload.cjs'), 'utf8'); -const names = new Set([...preload.matchAll(/([A-Za-z_$][\w$]*):t\(\)\.(?:args|noArgs)/g)].map(match => match[1])); +const { main: names, others } = desktopEdges(await readFile(path.join(payload, 'electron-preload/preload.cjs'), 'utf8')); +// The desktop mount panels and Spotlight are official windows this client never opens. +for (const [edge, methods] of others) { + const failure = { code: 'edge/unknown-method', detail: `The local client does not provide ${edge}` }; + for (const method of methods) ipcMain.handle(`dune-rpc:${edge}:m:${method}`, () => ({ ok: false, failure })); + ipcMain.handle(`dune-rpc:${edge}:probe`, event => ({ ok: Boolean(trusted(event, mainWindow)), value: false })); +} for (const method of names) ipcMain.handle(`dune-rpc:main:m:${method}`, async (event, args) => { if (!trusted(event, mainWindow)) return { ok: false, failure: { code: 'edge/untrusted', detail: 'Unexpected renderer' } }; try { @@ -299,20 +350,27 @@ for (const method of names) ipcMain.handle(`dune-rpc:main:m:${method}`, async (e return { ok: true, value: await methodCall(method, args) }; } catch (error) { return { ok: false, failure: { code: 'edge/handler-failed', detail: error.message } }; } }); -ipcMain.handle('dune-rpc:main:probe', (event, method) => ({ ok: trusted(event, mainWindow), value: names.has(method) })); +ipcMain.handle('dune-rpc:main:probe', (event, method) => probeLocalMethod(trusted(event, mainWindow), names, methodCall, method)); updateMenu(); app.on('activate', () => { if (starting) return; if (mainWindow) { mainWindow.show(); mainWindow.focus(); } - else if (!connectWindow) void (config ? showWorkspace() : showConnection()); + else if (!connectWindow) void (transport && config ? showWorkspace() : showConnection()); }); +if (isWindows) { + try { if (registerIntegration) ensureStartMenuShortcut({ app, shell }); } + catch (error) { console.warn('[shortcut]', error.message); } + tray = createTray({ Tray, Menu, nativeImage, clientRoot, show: () => void showApp(), quit: () => app.quit(), text: localText }); +} app.on('before-quit', () => { quitting = true; stopConnection(); void transport?.close(); }); // Activate the app for any Keychain prompt, then choose the first window from // the saved credentials. Dock activation must not open pairing during loading. app.focus(); -try { config = await store.load(); if (config) { transport = await openTransport(config.address ?? config.server, config.tailcat, { identity: config.networkIdentity, binary: transportBinary }); config = { ...config, ...transport }; } } -catch { connectionError = localText('无法读取设备凭证,请重新配对。', 'Could not read device credentials. Pair again.'); } -if (config) await showWorkspace(); +({ config, transport, connectionError } = await restoreConnection(store, transportBinary)); +if (transport && config) await showWorkspace(); else await showConnection(); starting = false; +// Windows starts a new process for a link when the client is not running yet. +const launchLink = initialLink(process.argv); +if (launchLink) routeLink(launchLink); }).catch(error => { console.error('[startup]', error); app.quit(); }); diff --git a/mac/clients/desktop/native-provider.mjs b/mac/clients/desktop/native-provider.mjs index 3dae3b1b471910417f693d8650963e01841dbae8..6239aad8c0a9cfa4c44dadd2db83a6dd9816c49c 100644 --- a/mac/clients/desktop/native-provider.mjs +++ b/mac/clients/desktop/native-provider.mjs @@ -31,7 +31,10 @@ export function startNativeProvider({ config, computer, onUnauthorized }) { ).catch(() => {}).finally(() => calls.delete(data.requestId)); } }; - void subscribe(config, '/desktop-capabilities/requests', accept, abort.signal, { + // Older Hosts assume macOS; other platforms name themselves so machine IDs match local execution. + const endpoint = process.platform === 'darwin' ? '/desktop-capabilities/requests' + : `/desktop-capabilities/requests?platform=${encodeURIComponent(process.platform)}`; + void subscribe(config, endpoint, accept, abort.signal, { onUnauthorized: () => { clear(); computer.close(); onUnauthorized?.(); }, onDisconnected: () => { clear(); computer.disconnected?.(); }, }); diff --git a/mac/clients/desktop/pairing-code.mjs b/mac/clients/desktop/pairing-code.mjs new file mode 100644 index 0000000000000000000000000000000000000000..74243a479266b97e354ff0614f5c4cf6686804b0 --- /dev/null +++ b/mac/clients/desktop/pairing-code.mjs @@ -0,0 +1,3 @@ +// The Host accepts separators; desktop IMEs can also emit full-width letters and digits. +export const normalizePairingCode = value => typeof value === 'string' + ? value.normalize('NFKC').replace(/[\s-]/g, '').toUpperCase() : ''; diff --git a/mac/clients/desktop/platform.mjs b/mac/clients/desktop/platform.mjs new file mode 100644 index 0000000000000000000000000000000000000000..573d21c4570fb062ae77500bdb0df253ec39418b --- /dev/null +++ b/mac/clients/desktop/platform.mjs @@ -0,0 +1,131 @@ +// Platform window chrome and shell integration. macOS keeps the original inset +// traffic lights; Windows uses the original frameless window with native caption +// buttons drawn by the title-bar overlay, a notification-area icon and a Start menu +// shortcut that carries the toast identity. +import path from 'node:path'; +import { linkSync, lstatSync, mkdtempSync, rmdirSync, unlinkSync } from 'node:fs'; +import { lstat, readFile } from 'node:fs/promises'; + +export const isWindows = process.platform === 'win32'; +export const APP_USER_MODEL_ID = 'dev.grokbot.local'; +export const SHORTCUT_NAME = 'Grok Bot Local.lnk'; + +// Values of the original Windows client: 52 px chrome minus its divider, and the +// modal dimming layers used while a sheet covers the window. +const OVERLAY_HEIGHT = 51, OVERLAY_TONE_HEIGHT = 43; +const COVER = { rgb: [20, 20, 20], alpha: 0.95 }, TOP_BAR = { rgb: [0, 0, 0], alpha: 0.55 }, FALLBACK = [24, 24, 24]; +const rgb = hex => /^#[0-9a-f]{6}$/i.test(hex) ? [1, 3, 5].map(at => Number.parseInt(hex.slice(at, at + 2), 16)) : undefined; +const blend = (layer, hex) => { + const base = rgb(hex) ?? FALLBACK; + return `#${layer.rgb.map((value, index) => Math.round(value * layer.alpha + base[index] * (1 - layer.alpha)) + .toString(16).padStart(2, '0')).join('')}`; +}; +const symbolColor = hex => { + const [red, green, blue] = rgb(hex) ?? FALLBACK; + return (red * 299 + green * 587 + blue * 114) / 1000 < 128 ? '#FFFFFF' : '#000000'; +}; + +export function titleBarOverlay(background, tone = false) { + const color = tone ? blend(TOP_BAR, blend(COVER, background)) : background; + return { color, symbolColor: symbolColor(color), height: tone ? OVERLAY_TONE_HEIGHT : OVERLAY_HEIGHT }; +} + +export function windowChrome(background, platform = process.platform) { + return platform === 'win32' + ? { frame: false, titleBarStyle: 'hidden', titleBarOverlay: titleBarOverlay(background) } + : { frame: true, titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 16, y: 15 } }; +} + +/** The pairing window keeps its 42 px drag strip on both platforms. */ +export function connectWindowChrome(platform = process.platform) { + return platform === 'win32' + ? { frame: false, titleBarStyle: 'hidden', titleBarOverlay: { color: '#111111', symbolColor: '#FFFFFF', height: 42 } } + : { titleBarStyle: 'hiddenInset', trafficLightPosition: { x: 16, y: 15 } }; +} + +/** Original window RPCs used by the Windows renderer's title bar. */ +export function windowHandlers(win, background, { platform = process.platform, workArea } = {}) { + let color = background, tone = false; + const windows = platform === 'win32'; + const apply = () => { if (windows && !win.isDestroyed()) win.setTitleBarOverlay(titleBarOverlay(color, tone)); }; + const state = () => ({ isFullscreen: win.isFullScreen(), isMaximized: win.isMaximized() }); + if (windows) for (const event of ['maximize', 'unmaximize', 'enter-full-screen', 'leave-full-screen']) + win.on(event, () => { if (!win.isDestroyed()) win.webContents.send('dune-rpc:main:e:window-state', state()); }); + return { + setBackground(value) { color = value; apply(); }, + handlers: windows ? { + getWindowState: state, + minimizeWindow: () => { win.minimize(); return null; }, + focusWindow: () => { win.show(); win.focus(); return null; }, + toggleMaximizeWindow: () => { if (win.isMaximized()) win.unmaximize(); else win.maximize(); return null; }, + closeWindow: () => { win.close(); return null; }, + resizeWindowWidth: ({ deltaWidth }) => { + if (!Number.isFinite(deltaWidth) || win.isMaximized() || win.isFullScreen()) return null; + const bounds = win.getBounds(), area = workArea?.(win) ?? bounds; + const width = Math.max(720, Math.min(area.width, Math.round(bounds.width + deltaWidth))); + win.setBounds({ ...bounds, width, x: Math.min(bounds.x, area.x + area.width - width) }); + return null; + }, + setTitleBarOverlayTone: ({ isOverlayTone }) => { tone = isOverlayTone === true; apply(); return null; }, + } : {}, + }; +} + +/** A side-by-side install shares userData, but the legacy install keeps the OS registrations. */ +export async function canRegisterDesktopIntegration({ isolatedProfile, platform = process.platform, execPath = process.execPath }) { + if (isolatedProfile) return false; + if (platform !== 'win32') return true; + const directory = path.dirname(execPath), file = path.join(directory, '.grokbot-installation.json'); + let stat; + try { stat = await lstat(file); } + catch (error) { return error.code === 'ENOENT'; } // Portable build: no installer receipt. + if (!stat.isFile() || stat.size > 4 * 1024 * 1024) return false; + try { + const receipt = JSON.parse(await readFile(file, 'utf8')); + return receipt.format === 1 && receipt.appId === APP_USER_MODEL_ID && + receipt.directory?.toLowerCase() === directory.toLowerCase() && !Object.hasOwn(receipt, 'sideBySideOf'); + } catch { return false; } +} + +/** Windows delivers toasts only for an app with a Start menu shortcut carrying its AppUserModelID. */ +export function ensureStartMenuShortcut({ app, shell, execPath = process.execPath }) { + const link = path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', SHORTCUT_NAME); + const stat = lstatSync(link, { throwIfNoEntry: false }); + if (stat) { + if (!stat.isFile()) return false; + let current; + try { current = shell.readShortcutLink(link); } catch { return false; } + if (typeof current?.target !== 'string' || path.resolve(current.target).toLowerCase() !== execPath.toLowerCase() || + current.appUserModelId === APP_USER_MODEL_ID) return false; + if (!shell.writeShortcutLink(link, 'update', { appUserModelId: APP_USER_MODEL_ID })) throw new Error('Could not update the Start menu shortcut'); + return true; + } + const options = { target: execPath, cwd: path.dirname(execPath), description: 'Grok Bot Local', + icon: execPath, iconIndex: 0, appUserModelId: APP_USER_MODEL_ID }; + // Electron's create mode overwrites. Publish the finished link only if the destination is still free. + const stage = mkdtempSync(path.join(path.dirname(link), '.grokbot-link-')), pending = path.join(stage, SHORTCUT_NAME); + try { + if (!shell.writeShortcutLink(pending, 'create', options)) throw new Error('Could not create the Start menu shortcut'); + try { linkSync(pending, link); } catch (error) { if (error.code === 'EEXIST') return false; throw error; } + return true; + } finally { + try { unlinkSync(pending); } catch (error) { if (error.code !== 'ENOENT') throw error; } + rmdirSync(stage); + } +} + +export function createTray({ Tray, Menu, nativeImage, clientRoot, show, quit, text }) { + const tray = new Tray(nativeImage.createFromPath(path.join(clientRoot, 'icon.ico'))); + tray.setToolTip('Grok Bot'); + tray.setContextMenu(Menu.buildFromTemplate([ + { label: text('打开 Grok Bot', 'Open Grok Bot'), click: show }, + { type: 'separator' }, + { label: text('退出', 'Quit'), click: quit }, + ])); + tray.on('click', show); + return tray; +} + +export function initialLink(argv) { + return argv.find(value => typeof value === 'string' && value.startsWith('grokbot-local:')) ?? null; +} diff --git a/mac/clients/desktop/preload.cjs b/mac/clients/desktop/preload.cjs index 872fd3bae4547bd6b4c1b1578252e089da10300c..b6403254cf20336b5144a0ed02c970c0f853b5a4 100644 --- a/mac/clients/desktop/preload.cjs +++ b/mac/clients/desktop/preload.cjs @@ -1,3 +1,4 @@ +require('./workspace-keys.cjs'); require('../dist/electron-preload/preload.cjs'); const { ipcRenderer, contextBridge } = require('electron'); contextBridge.exposeInMainWorld('localBot', { diff --git a/mac/clients/desktop/settings.mjs b/mac/clients/desktop/settings.mjs index 2bc9815ff40bdcea39b5ede59b28e772672eae4d..15db72e9e072d6911c242b1ed1d1b776bd7e4afb 100644 --- a/mac/clients/desktop/settings.mjs +++ b/mac/clients/desktop/settings.mjs @@ -8,7 +8,7 @@ export function loadSettings(profile) { try { return { ...defaults, ...JSON.parse(readFileSync(path.join(profile, 'settings.json'), 'utf8')) }; } catch { return { ...defaults }; } } -export function createSettings({ profile, window, app, nativeTheme, settings, enabledAtLaunch, command, theme, language, boot, onVoicePreference }) { +export function createSettings({ profile, window, app, nativeTheme, settings, enabledAtLaunch, command, theme, language, boot, onVoicePreference, onBackground }) { let writes = Promise.resolve(); const persist = () => { const snapshot = JSON.stringify(settings); @@ -26,7 +26,9 @@ export function createSettings({ profile, window, app, nativeTheme, settings, en }; const updateTheme = () => { Object.assign(theme, { preference: settings.theme, resolved: nativeTheme.shouldUseDarkColors ? 'dark' : 'light', systemAccentColor: null }); - if (!window.isDestroyed()) window.setBackgroundColor(theme.resolved === 'dark' ? '#111111' : '#ffffff'); + const background = theme.resolved === 'dark' ? '#111111' : '#ffffff'; + if (!window.isDestroyed()) window.setBackgroundColor(background); + onBackground?.(background); emit('theme-changed', theme); return { ...theme }; }; const updateLanguage = () => { diff --git a/mac/clients/desktop/sounds.mjs b/mac/clients/desktop/sounds.mjs index a7dc8b4074d7a599f7ff9f2f31b7b625a2df18e3..e0b2c84b9a5b6396cc498f7ca66fee2940020385 100644 --- a/mac/clients/desktop/sounds.mjs +++ b/mac/clients/desktop/sounds.mjs @@ -19,7 +19,13 @@ export async function createSounds(profile, payload) { return { play(sound) { if (!assets[sound]) return; - const child = spawn('/usr/bin/afplay', [path.join(directory, assets[sound])], { stdio: 'ignore' }); + const file = path.join(directory, assets[sound]); + // Windows has no command-line player; the system SoundPlayer reads the path from the environment. + const child = process.platform === 'win32' + ? spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', + '(New-Object System.Media.SoundPlayer $env:GROKBOT_SOUND_FILE).PlaySync()'], + { stdio: 'ignore', windowsHide: true, env: { ...process.env, GROKBOT_SOUND_FILE: file } }) + : spawn('/usr/bin/afplay', [file], { stdio: 'ignore' }); children.add(child); child.once('exit', () => children.delete(child)); child.once('error', () => children.delete(child)); }, stop() { for (const child of children) child.kill(); children.clear(); }, diff --git a/mac/clients/desktop/streams.mjs b/mac/clients/desktop/streams.mjs index a562e850da8c74a8f8e877422fd32a5863f7d7e6..97d401b67aab12ccac5fe293543df4d50ec55244 100644 --- a/mac/clients/desktop/streams.mjs +++ b/mac/clients/desktop/streams.mjs @@ -1,4 +1,20 @@ -import { setTimeout as delay } from 'node:timers/promises'; +const FIRST_RETRY_MS = 500, MAX_RETRY_MS = 10000, STABLE_STREAM_MS = 30000; + +function retryDelay(milliseconds, signal) { + if (signal.aborted) return Promise.reject(signal.reason); + return new Promise((resolve, reject) => { + const abort = () => { + clearTimeout(timer); + signal.removeEventListener('abort', abort); + reject(signal.reason); + }; + const timer = setTimeout(() => { + signal.removeEventListener('abort', abort); + resolve(); + }, milliseconds); + signal.addEventListener('abort', abort, { once: true }); + }); +} export async function readSse(body, consume) { let buffer = ''; @@ -21,8 +37,9 @@ export async function readSse(body, consume) { } export async function subscribe(config, endpoint, consume, signal, options = {}) { - let failures = 0, lastId = options.lastId ?? ''; + let retryMs = FIRST_RETRY_MS, lastId = options.lastId ?? ''; while (!signal.aborted) { + let openedAt; const request = new AbortController(); const abort = () => request.abort(signal.reason); signal.addEventListener('abort', abort, { once: true }); @@ -30,28 +47,35 @@ export async function subscribe(config, endpoint, consume, signal, options = {}) try { signal.throwIfAborted(); const response = await fetch(`${config.server}${endpoint}`, { - headers: { Authorization: `Bearer ${config.token}`, ...(lastId ? { 'Last-Event-ID': lastId } : {}) }, + headers: { Accept: 'text/event-stream', Authorization: `Bearer ${config.token}`, ...(lastId ? { 'Last-Event-ID': lastId } : {}) }, signal: request.signal, redirect: 'error', }); clearTimeout(timeout); + request.signal.throwIfAborted(); if (response.status === 401) { options.onUnauthorized?.(); return; } - if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`); - failures = 0; + if (response.status !== 200 || !response.body) throw new Error(`HTTP ${response.status}`); + const mediaType = response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase(); + if (mediaType !== 'text/event-stream') throw new Error('Expected a text/event-stream response'); + openedAt = performance.now(); options.onConnected?.(); await readSse(response.body, async frame => { + request.signal.throwIfAborted(); await consume(frame); - if (frame.id) lastId = frame.id; + if (frame.id !== undefined && !frame.id.includes('\0')) lastId = frame.id; }); throw new Error('事件连接结束'); } catch (error) { if (signal.aborted) return; + // A proxy can repeatedly send 200 and close, even after an initial snapshot. + if (openedAt !== undefined && performance.now() - openedAt >= STABLE_STREAM_MS) retryMs = FIRST_RETRY_MS; options.onDisconnected?.(error); } finally { clearTimeout(timeout); signal.removeEventListener('abort', abort); request.abort(); } - try { await delay(Math.min(500 * 2 ** Math.min(failures++, 4), 10000), undefined, { signal }); } + try { await retryDelay(retryMs, signal); } catch { return; } + retryMs = Math.min(retryMs * 2, MAX_RETRY_MS); } } diff --git a/mac/clients/desktop/workspace-keys.cjs b/mac/clients/desktop/workspace-keys.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c4078595a238655f25e15954f98555c34da5bb72 --- /dev/null +++ b/mac/clients/desktop/workspace-keys.cjs @@ -0,0 +1,27 @@ +// Loaded by Electron preload and served as a plain script by the Android bridge. +(() => { + if (window !== window.top) return; + const layers = 'dialog[open], [role="dialog"]:not([aria-modal="false"]), [role="alertdialog"]'; + window.addEventListener('keydown', event => { + const field = event.target; + if (event.key !== 'Escape' || event.isComposing || event.repeat || !field?.matches?.('input[role="combobox"][aria-autocomplete]') || field.value !== '') return; + const layer = field.closest(layers), close = layer?.querySelector('button.sand-plugins-dialog__close'); + if (!close || close.closest(layers) !== layer || close.disabled || !close.getClientRects().length) return; + event.preventDefault(); event.stopImmediatePropagation(); close.click(); + }, true); + function guard(event) { + if (event.key !== 'Enter' || !(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey || event.isComposing) return; + const visible = el => el.isConnected && !el.closest('[inert],[aria-hidden="true"]') && el.getClientRects().length > 0; + const layer = event.composedPath().find(el => el.nodeType === 1 && el.matches(layers) && visible(el)); + if (layer) { + // Let handlers on the control and dialog run; do not bubble to the background chat. + const contain = e => { if (e === event) e.stopPropagation(); }; + layer.addEventListener(event.type, contain); + setTimeout(() => layer.removeEventListener(event.type, contain), 0); + } else if ([...document.querySelectorAll(layers)].some(visible)) { + event.preventDefault(); event.stopImmediatePropagation(); + } + } + window.addEventListener('keydown', guard, true); + window.addEventListener('keyup', guard, true); +})(); diff --git a/mac/clients/desktop/workspace.css b/mac/clients/desktop/workspace.css new file mode 100644 index 0000000000000000000000000000000000000000..c0fa028268076fafb60fba6836cfa0527d19d4fe --- /dev/null +++ b/mac/clients/desktop/workspace.css @@ -0,0 +1,8 @@ +/* Wide tables can use the row beyond the prose cap. Keep room for hover actions. */ +@media (min-width: 600px) { + [role="log"] .sand-message:has(.sand-message-prose table) { + box-sizing: border-box; + width: max-content; + max-width: max(80%, calc(100% - 8rem)) !important; + } +} diff --git a/mac/dist/network/x64/grokbot-tailcat b/mac/dist/network/x64/grokbot-tailcat new file mode 100755 index 0000000000000000000000000000000000000000..7b6911792a4fc6dc426c3ecdfca76e727ebe1e33 Binary files /dev/null and b/mac/dist/network/x64/grokbot-tailcat differ diff --git a/mac/patchers/desktop/download-original.mjs b/mac/patchers/desktop/download-original.mjs index 7b1013ad7d70272ed0b77702767e2b2b5036a7dd..ece42bfd14ce10106b6ae230f89d269b7ed02eb0 100644 --- a/mac/patchers/desktop/download-original.mjs +++ b/mac/patchers/desktop/download-original.mjs @@ -19,7 +19,12 @@ async function matchesArchive(file, archive) { export async function acquireDesktopSource({ source, cacheDirectory, supported, fetchImpl = globalThis.fetch, onDownload = () => {} }) { - if (source) return path.resolve(source); + if (source) { + const file = path.resolve(source); + if (path.extname(file).toLowerCase() === '.dmg' && (!supported?.archive || !await matchesArchive(file, supported.archive))) + throw new Error('原版 DMG 整包摘要不匹配;不会挂载此文件。'); + return file; + } const archive = supported.archive; if (!archive?.url || !archive.bytes || !/^[a-f0-9]{64}$/.test(archive.sha256)) throw new Error('缺少原版下载信息。'); @@ -52,7 +57,7 @@ export async function acquireDesktopSource({ source, cacheDirectory, supported, await rename(partial, destination); return destination; } catch (error) { - throw new Error(`${error.message}\n请自行准备 Grok Bot ${supported.version} 原版 .app 或 .dmg,使用 --source 指定。\n原版地址:${archive.url}`, { cause: error }); + throw new Error(`${error.message}\n请自行准备 Grok Bot ${supported.version} 原版文件,使用 --source 指定。\n原版地址:${archive.url}`, { cause: error }); } finally { if (temporary) await rm(temporary, { recursive: true, force: true }); } diff --git a/mac/patchers/desktop/extract-policy.mjs b/mac/patchers/desktop/extract-policy.mjs index e08aad2983b753026f5e1a0a1579d6a5fffd3785..edfb0eb3609922e0a538c6dfe1f6f91595521301 100644 --- a/mac/patchers/desktop/extract-policy.mjs +++ b/mac/patchers/desktop/extract-policy.mjs @@ -15,5 +15,8 @@ export async function extractNotificationPolicy(unpacked, directory) { if (start < 0 || end <= start || end > source.length) throw new Error('原通知判定器字节区段无效'); const body = source.subarray(start, end); if (sha(body) !== policy.sha256) throw new Error('原通知判定器摘要不匹配'); - return Buffer.concat([body, Buffer.from('\nexport { QR as NotificationDecider };\n')]); + // Each build renames the minified class; the 0.71.2 records predate this field. + const name = policy.exportName ?? 'QR'; + if (!/^[A-Za-z_$][\w$]*$/.test(name)) throw new Error('原通知判定器导出名无效'); + return Buffer.concat([body, Buffer.from(`\nexport { ${name} as NotificationDecider };\n`)]); } diff --git a/mac/patchers/desktop/native-helper.mjs b/mac/patchers/desktop/native-helper.mjs index 0a31a98c59338231a07a77c99b225696d0215601..f528bf17ead1bce5b778711a6fdda2d6dff6039c 100644 --- a/mac/patchers/desktop/native-helper.mjs +++ b/mac/patchers/desktop/native-helper.mjs @@ -3,12 +3,17 @@ import { createHash } from 'node:crypto'; // Grok Bot 0.71.2 universal helper: Swift Array backing the stdio // peer policy, one entry in each architecture. The UID/signature checks stay intact. -const digest = 'ebcb4aeba02914e0cf073fd3493b2c1235b73814fe60fd7854c296591b68bbc5'; +// The Apple Silicon and Intel downloads carry separately signed builds of the same +// universal helper, with the team at the same offsets. +const digests = new Set([ + 'ebcb4aeba02914e0cf073fd3493b2c1235b73814fe60fd7854c296591b68bbc5', // darwin-arm64 DMG + 'c337d70faba610cbc78f437b9e19be40d8dbd68fb72c59643daf8263ad2a76b3', // darwin-x64 DMG +]); const teamOffsets = [0x1a0e58, 0x4a5c88]; export async function patchNativeHelperTeam(filename, teamId) { if (!/^[A-Z0-9]{10}$/.test(teamId)) throw new Error('Computer helper requires a certificate Team ID'); const bytes = await readFile(filename); - if (createHash('sha256').update(bytes).digest('hex') !== digest) throw new Error('Unsupported computer helper binary'); + if (!digests.has(createHash('sha256').update(bytes).digest('hex'))) throw new Error('Unsupported computer helper binary'); for (const offset of teamOffsets) { if (bytes.subarray(offset, offset + 10).toString() !== 'DCNK4UB866' || bytes[offset + 15] !== 0xea) throw new Error('Computer helper peer policy fingerprint mismatch'); diff --git a/mac/patchers/desktop/node_modules/.package-lock.json b/mac/patchers/desktop/node_modules/.package-lock.json index fb117107d573cb91e2be54c04dcc29d9d660be73..4c638f3ced35cb0d9b3560cdcbed0d9894fb7c6f 100644 --- a/mac/patchers/desktop/node_modules/.package-lock.json +++ b/mac/patchers/desktop/node_modules/.package-lock.json @@ -4,13 +4,13 @@ "requires": true, "packages": { "node_modules/@electron/asar": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-4.3.1.tgz", - "integrity": "sha512-6pI64z/tMSBkUTZLQFYhs2YiB7fS9sKA6gy7/2nH1Ju7GGwT32UPsj4Mxsws5NMmtR6C0zYdXVxEU/rGqJRCJA==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-4.3.2.tgz", + "integrity": "sha512-2nwyO3OgmLgkYQe6TzB8FmyrBKGgmXzSO51ozoG2BpHOLPTPdQpBt/zD0MdPkhQr4UqVgw3u09y4uYxgZKhmtg==", "license": "MIT", "dependencies": { - "glob": "^13.0.2", - "minimatch": "^10.0.1" + "glob": "^14.0.2", + "minimatch": "^11.0.1" }, "bin": { "asar": "bin/asar.mjs" @@ -19,6 +19,12 @@ "node": ">=22.12.0" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "license": "BlueOak-1.0.0" + }, "node_modules/balanced-match": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", @@ -29,9 +35,9 @@ } }, "node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" @@ -41,14 +47,14 @@ } }, "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "version": "14.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz", + "integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==", "license": "BlueOak-1.0.0", "dependencies": { - "minimatch": "^10.2.2", + "minimatch": "^11.0.5", "minipass": "^7.1.3", - "path-scurry": "^2.0.2" + "path-scurry": "^3.0.0" }, "engines": { "node": "18 || 20 || >=22" @@ -67,15 +73,16 @@ } }, "node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^5.0.8" + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -91,9 +98,9 @@ } }, "node_modules/path-scurry": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", - "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", + "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", "license": "BlueOak-1.0.0", "dependencies": { "lru-cache": "^11.0.0", diff --git a/mac/patchers/desktop/node_modules/@electron/asar/package.json b/mac/patchers/desktop/node_modules/@electron/asar/package.json index 1055866e5fcc211bd37edfcd474de689798034a0..d1992ae23c21bb0f83bf0a62ac4c53d990defd4f 100644 --- a/mac/patchers/desktop/node_modules/@electron/asar/package.json +++ b/mac/patchers/desktop/node_modules/@electron/asar/package.json @@ -1,7 +1,7 @@ { "name": "@electron/asar", "description": "Creating Electron app packages", - "version": "4.3.1", + "version": "4.3.2", "type": "module", "exports": "./lib/asar.js", "types": "./lib/asar.d.ts", @@ -34,14 +34,14 @@ "test:ui": "vitest --ui", "lint": "oxfmt --check . && oxlint", "lint:fix": "oxfmt --write . && oxlint --fix", - "benchmark": "yarn build && tsx benchmark/run.ts", - "benchmark:quick": "yarn build && tsx benchmark/run.ts small", + "benchmark": "yarn build && node --experimental-strip-types benchmark/run.ts", + "benchmark:quick": "yarn build && node --experimental-strip-types benchmark/run.ts small", "prepack": "yarn build", "prepare": "husky" }, "dependencies": { - "glob": "^13.0.2", - "minimatch": "^10.0.1" + "glob": "^14.0.2", + "minimatch": "^11.0.1" }, "devDependencies": { "@tsconfig/node22": "^22.0.1", @@ -49,14 +49,13 @@ "electron": "^43.0.0", "husky": "^9.1.7", "lint-staged": "^17.4.1", - "oxfmt": "^0.44.0", + "oxfmt": "^0.71.0", "oxlint": "^1.59.0", "oxlint-tsgolint": "^0.20.0", - "tsx": "^4.21.0", "typedoc": "~0.28.0", "typescript": "^6.0.2", "vite": "^8.0.16", - "vitest": "^5.0.1", + "vitest": "^5.0.5", "xvfb-maybe": "^0.2.1" }, "resolutions": { diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/LICENSE.md b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..c5402b9577a8cdd966c0974e5b74cc7b85f536c5 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/LICENSE.md @@ -0,0 +1,55 @@ +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +***As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim.*** diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/README.md b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0cc57ca2bc5f8157ddc5d250fe9b2de187b8043b --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/README.md @@ -0,0 +1,364 @@ +# @isaacs/nonrecursive-glob-match + +This is a glob matcher that can be applied to a single path +portion (ie, not `/`), which completes in polynomial time because +it doesn't compile to Regular Expressions or any other +backtrack-dependent algorithm. + +## USAGE + +```ts +import { Matcher } from '@isaacs/nonrecursive-glob-match' + +const m = new Matcher('a*a!(y|z)') + +console.log(m.test('abcay')) // false +console.log(m.test('abcax')) // true +console.log(m.test('aa')) // true +``` + +The pattern and the tested string must be a single path portion. +If either one contains a `/` character, the matcher throws an +error. + +If you already split a path on `/`, use `m.testUnchecked(s)`. It +gives the same result as `m.test(s)`, but it does not check `s` +for a `/` character. This can make it faster, because some +patterns, such as `*.js`, then do not need to look at each +character. If `s` has a `/`, the result is not defined. + +## Why + +Patterns like this frustrate most glob matchers: `a*a*a*a*a*a*a`. +They can be used to take down servers if applied to untrusted +input. Fixing these vulns is like playing whack-a-mole with the +whole internet. + +If compiled to a regular expression like +`/^a[^/]*a[^/]*a[^/]*a[^/]*a[^/]*a[^/]*a$/`, and then applied to +a path portion like `aaaaaaaaaaaaaaaaaaab`, the engine must check +every possible path through the pattern, constantly rewinding +back to the first character each time and trying a different +number of `a` characters matched against the `[^/]*` to see if it +matches. Because nothing matches, it must test every possible +path before ultimately giving up. + +In contrast, the algorithm presented here is based on the +Thompson NFA paper from 1968, which tests every possible path +through the string at the same time, so that it only has to walk +the string one time. This algorithm is also implemented in the +RegExp engines used by `egrep` and `awk`, which is why those +tools are so fast, even when matching complicated RegExps against +extremely large strings. + +The `Matcher` objects have a `test` method which takes a string, +just like a `RegExp` object, and can be a drop-in replacement for +the regular expressions used in minimatch and other matchers. +However, they are _not_ a complete drop-in replacement for a +RegExp, so be careful when replacing one with the other. (For +example, they do not capture, do not track match indexes, no +fancy RegExp features, etc.) + +## Patterns Supported + +Here are the patterns supported, and their effective state +machines drawn in lovely ASCII diagrams. + +### `*` 0 or more of any character, not starting with `.` + +``` +--+-------------------+-> + v ^ + +<------------------+ + v ^ + +-->any character-->+ +``` + +### `?` + +``` +-->any character--> +``` + +### `[]` + +``` +-->character in set--> +``` + +This covers named posix sets like `[[:alpha:]]` as well as +character classes like `[a-b]`. (In this case, a regular +expression actually is compiled, but it's not subject to ReDoS, +becuase it's just a `/[a-z]/` style pattern tested against one +character at a time.) + +### `@(e1|e2|...)` + +"One" extglob. + +``` +--+--> e1 -->+--> + v ^ + +--> e2 -->+ + v ^ + +--> e3 -->+ + v ... ^ +``` + +### `?(e1|e2|...)` + +"Zero or one" extglob. + +``` +--+--------->+--> + v ^ + +--> e1 -->+ + v ^ + +--> e2 -->+ + v ^ + +--> e3 -->+ + v ... ^ +``` + +### `*(e1|e2|...)` + +"Zero or more" extglob. + +``` +--+--------->+--> + v ^ + +<---------+ + v ^ + +--> e1 -->+ + v ^ + +--> e2 -->+ + v ^ + +--> e3 -->+ + v ... ^ +``` + +### `+(e1|e2|...)` + +"One or more" extglob. + +``` + +<---------+ + v ^ +--+--> e1 -->+--> + v ^ + +--> e2 -->+ + v ^ + +--> e3 -->+ + v ... ^ +``` + +### `!(e1|e2|...)` + +"Negative" extglob. + +The challenge with negation is that it opens the door to a whole +heap of edge cases. Especially, _any_ expression can be nested +inside the negation, and it needs to match anything at all, as +long as it _doesn't_ match one of the supplied patterns. This is +where it gets complicated, and past attempts have run into +problems. + +We handle this by starting a "Run" that technically does recurse, +and thus can push the performance out from `O(n * m)` to +`O(n * m * r)` where `n` is the string length, `m` is the pattern +length, and `r` is the number of negative extglob portions it +contains. In practice, this is limited by the pattern length, and +still doesn't allow ReDOS-style explosive recursive backtracking, +so this is fine. + +## Unicode Normalization + +A char such as `é` can be one code point (U+00E9), or `e` +followed by a combining accent (U+0301). Some file systems, such +as on macOS, can give file names in the second form. These two +forms do not match by default. + +Set the `normalize` option to normalize the pattern and each +tested string to the same form. Use `'NFC'`, `'NFD'`, `'NFKC'`, +or `'NFKD'`. `true` means `'NFC'`. + +```ts +const m = new Matcher('café', { normalize: true }) +m.test('café') // true +``` + +- Use NFC if you are not sure. With NFD and NFKD, `é` is two + code points. Then `?` does not match `é`, and `[é]` can not + match it. +- NFKC and NFKD also fold compatibility chars. For example, `fi` + matches `fi`, and full-width `A` matches `A`. +- Syntax is parsed before normalization. So, a char that + normalizes to a syntax char stays a literal. For example, with + NFKC, full-width `*` matches only `*` or `*`, and it is not a + wildcard. +- Each run of literal chars normalizes as one string. Each member + of a `[...]` class normalizes on its own, and stays as it is if + its normal form is more than one code point. +- A combining mark after a wildcard is its own literal, and does + not compose with the char that the wildcard matches. So, with + NFC, `?́` does not match `é`. With NFD, it does match, + because `é` is also two code points in the string. Patterns + match code points, not grapheme clusters. +- With `nocase`, normalization comes first, then case folding. +- The `/` check uses the strings as given. So, full-width `/` + does not cause an error. + +## Numeric Ranges + +Bash brace expansion makes `{1..1000}` into 1000 words. A glob +library that expands braces before matching, such as +[minimatch](http://npm.im/minimatch), can use the `rangeMark` +option to match a range in one pattern instead. + +Set `rangeMark` to a char that is not otherwise in the pattern. +Then `..` matches the same strings as the +brace expansion `{..}`, where `lo` and `hi` are integers. +If either end has a leading zero, each number has leading zeros to +make it as long as the longer end, counting a `-` sign. + +```ts +const M = '\uE000' +const m = new Matcher(`file-${M}001..500${M}.txt`, { + rangeMark: M, +}) +m.test('file-042.txt') // true +m.test('file-42.txt') // false +m.test('file-501.txt') // false +``` + +The range is matched with a few digit classes, so a large range +costs about the same as a small one. + +- A `\` before the mark does not escape it. +- Inside a `[...]` class, the mark is a char of the class. +- A mark without a valid range after it, or without a closing + mark, is a literal char. + +## Differences from Bash + +Bash 5 is the reference for this module, with two known +deviations. + +### Dotfiles + +If `dot` is not set, a string that starts with `.` only matches +if a literal `.` in the pattern matches that first character. +Extglobs before that `.` can match the empty string, and the +pattern can still match. For example, `!(.a|js)@(.*)` matches +`.a`, `.a.js`, and `.js`, because `!(.a|js)` matches the empty +string, and `@(.*)` matches the rest. Bash does not match these +dotfiles. See [this bug +report](https://lists.gnu.org/archive/html/bug-bash/2026-03/msg00034.html). + +A `*` can never match at the start of a dotfile, even if it +matches the empty string. So, `*.js` does not match `.js`, as in +Bash. + +### Case-insensitive matching + +Bash compares chars with the case functions of the C library for +the current locale. So, the results can change with the locale +and the platform. + +With `nocase`, this module uses Unicode simple case folding, one +code point at a time. This is the same folding that a JavaScript +RegExp uses with the `iu` flags. It does not change with the +locale, and literals, `[...]` classes, and ranges all use it. + +- `Σ`, `σ`, and final sigma `ς` all match each other. +- The micro sign `µ` matches `μ` and `Μ`. The Kelvin sign `K` + matches `k`. The Angstrom sign `Å` matches `å`. +- `ẞ` matches `ß`, but `ß` does not match `ss`. A fold never + changes the number of chars, so ligatures such as `fi` do not + match `fi`. +- There are no Turkish rules. `I` matches `i`, but dotted `İ` + and dotless `ı` only match themselves. + +## Algorithm + +A glob pattern is parsed and compiled into a series of attached +state machines. + +For example, the glob patttern `*(a|[c-d]|+(x|y|z))z` would +compile to a state machine something like the following flow +diagram: + +``` +-->+----------------------->+-->8 LITERAL(z)-->9 end + v ^ + +<-----------------------6 + v ^ + 0-->LITERAL(a)---------->| + v | + 1-->CLASS(c-d)---------->| + v | + 2-->+<---------------+-->+ + v ^ + 3-->LITERAL(x)-->7 + v | + 4-->LITERAL(y)-->| + v | + 5-->LITERAL(z)-->+ +``` + +Then, for each character in the string, we walk through the +resulting graph until we find a test node. + +These test nodes are all executed on the current character, and +for any tests pass, their output nodes are added to the walk, and +we proceed to walk until hitting a test node again. + +Because all routes eventually get to the exit, which only passes +when the string is at its last character, we are guaranteed to +eventually either fail (and have no more states to process), or +exit with a match. + +At each branching point, effectively we increase the memory usage +by a tiny bit to track which nodes are being processed, but +importantly, we _don't_ have to try all the way to the exit and +then backtrack recursively, storing multiple states of the string +in an exponential explosion. + +A pattern like `a*a*a*a*a*a*a*a*a*a*a`, which could be naively +converted into a Regular Expression +`^a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a$`, would take over 33 seconds +to match the string `'a'.repeat(50) + 'b'` using standard +JavaScript regular expressions, because it must attempt every +possible grouping of characters, backtracking after each failure. + +By contrast, this implementation can solve this match for either +a pass or failure in roughly the same amount of time, which +is bound by `C * N`, where `C` is the number of states in the +machine, and `N` is the length of the string, finishing both +failure and success cases in polynomial time. + +Even on the first rather naive implementation in JavaScript, with +no optimizations for repeated `*` or other common tweaks, this +finishes in 300-400 µs for the pathological case described, and +as the numbers increase, this time rises roughly linearly. + +That's somewhat worse than RegExp's performance in the _success_ +case, which is around 40µs, but as it's around 100,000x faster in +the failure case, this is already quite promising. And, future +iterations of this can likely bring that performance closer to +the native RegExp implementation. + +## Acknowledgement + +The algorithm and ideas in this implementation are inspired, +borrowed, and at times outright stolen from [Russ +Cox](https://research.swtch.com)'s explanation of Ken Thompson's +work in [Regular Expression Matching Can Be Simple And +Fast](https://swtch.com/~rsc/regexp/regexp1.html). I am both +impressed by and grateful for their work. + +The code here in this library was written entirely by me, [Isaac +Z. Schlueter](https://izs.me), and so you should not blame either +of them (or anyone else) for any problems it might have. You +should also not blame me. It's open source, after all, no +warrantees express or implied, etc. diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.d.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8353cdbc8a5a11e120d8df5476a51b45bdc98cc --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.d.ts @@ -0,0 +1,123 @@ +import { type Form } from './parse-class.js'; +export type { Form }; +export type MatcherOptions = { + /** perform a case-insensitive match */ + nocase?: boolean; + /** do not treat strings starting with `.` specially */ + dot?: boolean; + /** do not match extglobs (treat them as normal strings) */ + noext?: boolean; + /** + * normalize unicode in the pattern and the tested strings, with + * this form. `true` means `'NFC'`. + */ + normalize?: boolean | Form; + /** + * A char that marks a numeric range in the pattern, as + * `..`, where `lo` and `hi` are integers. It + * matches the strings that the bash brace expansion `{..}` + * makes, such as `{1..100}` or `{001..100}`, without making each + * one. A mark is never escaped by a `\` before it. Inside a `[...]` + * class, a mark is a char of the class. + */ + rangeMark?: string; +}; +export type Item = { + t: 'lit'; + ch: string; +} | { + t: 'any' | 'star'; +} | { + t: 'class'; + re: RegExp; +} | { + t: 'ext'; + type: string; + alts: Item[][]; +}; +export type Token = Item | { + t: 'open'; + type: string; +} | { + t: 'bar'; +} | { + t: 'close'; +}; +export type NegNode = { + t: 'neg'; + id: number; + sub: Node; + next: Node; +}; +export type SplitNode = { + t: 'split'; + id: number; + out: Node[]; +}; +export type Node = ({ + t: 'lit'; + id: number; + next: Node; +} & Lit) | { + t: 'any' | 'star'; + id: number; + next: Node; +} | { + t: 'class'; + id: number; + re: RegExp; + next: Node; +} | SplitNode | NegNode | { + t: 'match'; + id: number; +}; +/** + * A literal char. With `nocase:true`, `re` folds case, and `ascii` + * holds its results for ASCII chars, by char code: 1 for a match, + * and 2 for not. + */ +export type Lit = { + ch: string; + re?: RegExp; + ascii?: Uint8Array; +}; +/** + * For each node id, the gen of the last state that has the node as + * a thread, and of the last state that walked through it. A state is + * built to the end before the states around it go on, and the nodes + * of a negated sub-pattern are only in its states (other than the + * match node, which is never marked). So one mark for each node is + * enough to know if the state being built has it. The Sims of a + * matcher never run at the same time, so they share one Marks. + */ +export type Marks = { + has: Float64Array; + seen: Float64Array; + gen: number; +}; +/** + * A node in a graph with no splits or negations. Such a graph is a + * chain of nodes that each match one char, or a `*`. + */ +export type LinearNode = Exclude; +export declare class Matcher { + #private; + pattern: string; + options: MatcherOptions; + constructor(pattern: string, options?: MatcherOptions); + test(s: string): boolean; + /** + * The same as {@link Matcher#test}, but the string is not checked + * for `/` chars, so the result for a string that has one is not + * defined. Only use it for a string that is known to be one path + * portion, such as a part of a path that was split on `/`. It can + * be faster, because some patterns do not need to look at each char + * of the string. + */ + testUnchecked(s: string): boolean; + /** a readable listing of the state machine */ + toString(): string; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.d.ts.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..67993640d5ac0f5c3ae4b6910cab2dc96e04affc --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,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C9C,QAAQ,IAAI,MAAM;CAGnB"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.js b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..811157eac49a74f2e400cdc96eaa28108353922d --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.js @@ -0,0 +1,778 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Matcher = void 0; +const numeric_range_js_1 = require("./numeric-range.js"); +const parse_class_js_1 = require("./parse-class.js"); +// the end of the pattern, or of a negated sub-pattern +const MATCH = { t: 'match', id: 0 }; +const extTypes = '!?+*@'; +const lit = (ch) => ({ t: 'lit', ch }); +const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&'); +// a RegExp that only matches `s`, with unicode case folding +const newFoldRe = (s) => new RegExp(`^${reEscape(s)}$`, 'iu'); +// foldRe for one literal char. The same chars are in most patterns, +// so keep them. A RegExp without the `g` or `y` flag has no state to +// share. +const foldCache = new Map(); +const foldRe = (ch) => { + let re = foldCache.get(ch); + if (!re) { + re = newFoldRe(ch); + if (foldCache.size >= 1000) + foldCache.clear(); + foldCache.set(ch, re); + } + return re; +}; +const litMatch = (l, c) => { + if (c === l.ch) + return true; + if (!l.re) + return false; + const code = c.charCodeAt(0); + if (code >= 128) + return l.re.test(c); + const ascii = (l.ascii ??= new Uint8Array(128)); + ascii[code] ||= l.re.test(c) ? 1 : 2; + return ascii[code] === 1; +}; +const tokenize = (p, nocase, noext, form, mark) => { + const toks = []; + for (let i = 0; i < p.length;) { + const c = String.fromCodePoint(p.codePointAt(i)); + if (mark) { + // a \ before a range would only escape its first char + const m = c === '\\' && p.startsWith(mark, i + 1) ? 1 : 0; + if (m || c === mark) { + const start = i + m + mark.length; + const end = p.indexOf(mark, start); + const r = /^(-?\d+)\.\.(-?\d+)$/.exec(p.slice(start, end)); + const alts = end !== -1 && r && (0, numeric_range_js_1.numericRange)(r[1], r[2]); + if (alts) { + toks.push({ t: 'ext', type: '@', alts }); + i = end + mark.length; + continue; + } + } + } + if (c === '\\') { + // a trailing \ is a literal \ + const e = p.codePointAt(i + 1); + const ch = e === undefined ? c : String.fromCodePoint(e); + toks.push(lit(ch)); + i += 1 + ch.length; + continue; + } + if (c === '[') { + const [re, consumed] = (0, parse_class_js_1.parseClass)(p, i, nocase, form); + if (consumed) { + toks.push({ t: 'class', re }); + i += consumed; + continue; + } + } + if (!noext && extTypes.includes(c) && p[i + 1] === '(') { + toks.push({ t: 'open', type: c }); + i += 2; + continue; + } + toks.push(!noext && c === '|' ? { t: 'bar' } + : !noext && c === ')' ? { t: 'close' } + : c === '*' ? { t: 'star' } + : c === '?' ? { t: 'any' } + : lit(c)); + i += c.length; + } + return toks; +}; +// map each open token index to the index of its close token +const pair = (toks) => { + const pairs = new Map(); + const stack = []; + toks.forEach((tok, i) => { + if (tok.t === 'open') + stack.push(i); + else if (tok.t === 'close' && stack.length) + pairs.set(stack.pop(), i); + }); + return pairs; +}; +// build the alternatives between start and end. An open token that +// is not closed is never inside a closed extglob, so bar and close +// tokens are only literal at the top level. +const build = (toks, pairs, start, end, top) => { + let seq = []; + const alts = [seq]; + for (let i = start; i < end; i++) { + const tok = toks[i]; + const close = pairs.get(i); + if (tok.t === 'open' && close !== undefined) { + const sub = build(toks, pairs, i + 1, close, false); + seq.push({ t: 'ext', type: tok.type, alts: sub }); + i = close; + } + else if (tok.t === 'bar' && !top) { + alts.push((seq = [])); + } + else if (tok.t === 'open') { + seq.push(lit(tok.type), lit('(')); + } + else if (tok.t === 'bar') { + seq.push(lit('|')); + } + else if (tok.t === 'close') { + seq.push(lit(')')); + } + else { + seq.push(tok); + } + } + return alts; +}; +// normalize each run of literal chars as one string, so that a char +// and the combining marks after it compose (or decompose) together. +// Syntax is already parsed, so a char that normalizes to a syntax +// char (such as full-width `*` in NFKC) stays a literal. +const normalize = (items, form) => { + const out = []; + let run = ''; + const flush = () => { + for (const ch of run.normalize(form)) + out.push(lit(ch)); + run = ''; + }; + for (const it of items) { + if (it.t === 'lit') { + run += it.ch; + continue; + } + flush(); + out.push(it.t === 'ext' ? + { ...it, alts: it.alts.map(a => normalize(a, form)) } + : it); + } + flush(); + return out; +}; +// the start node, and the number of node ids. Ids are dense, from 0 +// for the match node. +const compile = (items, nocase) => { + let id = 1; + const split = (out) => ({ t: 'split', id: id++, out }); + const seq = (items, next) => items.reduceRight((next, it) => item(it, next), next); + const item = (it, next) => { + switch (it.t) { + case 'lit': + const re = nocase ? foldRe(it.ch) : undefined; + return { t: 'lit', id: id++, ch: it.ch, re, next }; + case 'any': + case 'star': + return { t: it.t, id: id++, next }; + case 'class': + return { t: 'class', id: id++, re: it.re, next }; + } + const alts = (next) => it.alts.map(a => seq(a, next)); + switch (it.type) { + case '@': + return split(alts(next)); + case '?': + return split([next, ...alts(next)]); + case '!': + return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }; + } + // * and +, loop back after each match + const after = split([]); + const entry = split(alts(after)); + after.out.push(next, entry); + return it.type === '*' ? after : entry; + }; + const start = seq(items, MATCH); + return [start, id]; +}; +// one line per node, in the order that a walk from the start +// reaches them. Edges point to node ids. The nodes of a negated +// sub-pattern are indented under their negation. +const show = (start) => { + const lines = []; + const seen = new Set(); + const ref = (n) => (n.t === 'match' ? 'match' : String(n.id)); + const walk = (n, indent) => { + if (n.t === 'match' || seen.has(n)) + return; + seen.add(n); + const line = (desc) => lines.push(`${indent}${n.id}: ${desc}`); + switch (n.t) { + case 'split': + line(`split -> ${n.out.map(ref).join(', ')}`); + for (const o of n.out) + walk(o, indent); + return; + case 'neg': + line(`!(${ref(n.sub)}) -> ${ref(n.next)}`); + walk(n.sub, indent + ' '); + return walk(n.next, indent); + case 'lit': + line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`); + break; + case 'class': + line(`${n.re} -> ${ref(n.next)}`); + break; + default: + line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`); + } + walk(n.next, indent); + }; + walk(start, ''); + return [`start -> ${ref(start)}`, ...lines].join('\n'); +}; +// The threads at one position in the string. Each node thread is +// only kept once, and runs with the same state are only kept once, +// so that identical threads merge. The match node is not in +// `threads`, because it can not step. It sets `match` instead. +class State { + // set by the Sim, to mark the nodes that this state has + gen; + threads = []; + match = false; + runs = []; + // the sorted ids of the threads, with 0 for a match, once the + // state is done + ids = []; + constructor(gen) { + this.gen = gen; + } + // no threads, so nothing more can match + get dead() { + return !this.threads.length && !this.match && !this.runs.length; + } +} +// true if the two states hold the same threads +const sameState = (a, b) => { + if (a.ids.length !== b.ids.length) + return false; + if (a.runs.length !== b.runs.length) + return false; + if (a.ids.some((id, i) => id !== b.ids[i])) + return false; + return a.runs.every(r => b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state))); +}; +const marks = (size) => ({ + has: new Float64Array(size), + seen: new Float64Array(size), + gen: 0, +}); +class Sim { + // `.` and `..` only match literal dots, even with `dot:true` + dots; + // the string starts with `.`, and `dot:true` is not set + dotStart; + #marks; + constructor(dots, dotStart, marks) { + this.dots = dots; + this.dotStart = dotStart; + this.#marks = marks; + } + state() { + return new State(++this.#marks.gen); + } + // sort the ids of a state, once it has all of its threads + done(state) { + state.ids = state.threads.map(n => n.id).sort((a, b) => a - b); + if (state.match) + state.ids.unshift(MATCH.id); + return state; + } + // true the first time that the state walks through the node, so + // that loops in the graph stop + #visit(state, node) { + const { seen } = this.#marks; + if (seen[node.id] === state.gen) + return false; + seen[node.id] = state.gen; + return true; + } + #addThread(state, node) { + const { has } = this.#marks; + if (has[node.id] === state.gen) + return false; + has[node.id] = state.gen; + state.threads.push(node); + return true; + } + // wildcards only match a leading dot if `dot:true`. In a negated + // sub-pattern, this does not apply, because the negation itself + // can not match a leading dot. + restricted(i, top) { + return top && (this.dots || (this.dotStart && i === 0)); + } + add(state, node, i, top) { + switch (node.t) { + case 'split': + if (!this.#visit(state, node)) + return; + for (const o of node.out) + this.add(state, o, i, top); + return; + case 'neg': + if (!this.#visit(state, node)) + return; + const sub = this.state(); + this.add(sub, node.sub, i, false); + this.done(sub); + return this.addRun(state, { t: 'run', neg: node, state: sub }, i, top); + case 'star': + // a * can not start a dotfile, even if it matches nothing + if (this.restricted(i, top)) + return; + if (this.#addThread(state, node)) + this.add(state, node.next, i, top); + return; + case 'match': + state.match = true; + return; + default: + this.#addThread(state, node); + } + } + addRun(state, run, i, top) { + for (const r of state.runs) { + if (r.neg === run.neg && sameState(r.state, run.state)) + return; + } + state.runs.push(run); + if (!run.state.match) { + this.add(state, run.neg.next, i, top); + } + } + // the threads after char `c`, at index `i` + step(state, c, i, top) { + const next = this.state(); + for (const th of state.threads) { + switch (th.t) { + case 'lit': + if (litMatch(th, c)) { + this.add(next, th.next, i + 1, top); + } + break; + case 'any': + if (!this.restricted(i, top)) + this.add(next, th.next, i + 1, top); + break; + case 'class': + if (!this.restricted(i, top) && th.re.test(c)) { + this.add(next, th.next, i + 1, top); + } + break; + case 'star': + if (!this.restricted(i, top)) + this.add(next, th, i + 1, top); + } + } + if (!this.restricted(i, top)) { + for (const run of state.runs) { + // a sub-pattern with no threads can not match again, so the + // run stays the same + if (run.state.dead) { + this.addRun(next, run, i + 1, top); + continue; + } + const sub = this.step(run.state, c, i, false); + this.addRun(next, { t: 'run', neg: run.neg, state: sub }, i + 1, top); + } + } + return this.done(next); + } +} +// A canonical key for the threads in a state. States with the same +// key hold the same threads, so they match the same strings. +const stateKey = (state) => { + const ids = state.ids.join(); + if (!state.runs.length) + return ids; + const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`); + return `${ids}|${runs.sort().join('|')}`; +}; +// The cache can hold about this many chars of state keys and +// transitions. When it is full, it is cleared, so that a pattern +// can not use an unbounded amount of memory. +const DFA_BUDGET = 1 << 18; +// A cache of the states that the simulation reaches, built as the +// matcher is used. Each char of a string is then one Map lookup, +// once the states that it leads to are known. +// +// The dot rules only restrict the first char of a dotfile (strings +// that are only `.` or `..` do not use the cache). So a dotfile +// starts at its own state, which takes its first step with the +// restriction, and every other state takes steps without it. +class Dfa { + #start; + #states = new Map(); + #size = 0; + #plain; + #dotStart; + #sim; + #dotSim; + constructor(start, marks) { + this.#start = start; + this.#sim = new Sim(false, false, marks); + this.#dotSim = new Sim(false, true, marks); + } + #make(state) { + return { + state, + match: state.match, + dead: state.dead, + next: new Map(), + }; + } + #intern(state) { + const key = stateKey(state); + const found = this.#states.get(key); + if (found) + return found; + if (this.#size > DFA_BUDGET) + this.#clear(); + const d = this.#make(state); + this.#states.set(key, d); + this.#size += key.length + 1; + return d; + } + #clear() { + this.#states.clear(); + this.#size = 0; + this.#plain = undefined; + this.#dotStart = undefined; + } + start(dotStart) { + if (dotStart) { + if (this.#dotStart) + return this.#dotStart; + const state = this.#dotSim.state(); + this.#dotSim.add(state, this.#start, 0, true); + return (this.#dotStart = this.#make(this.#dotSim.done(state))); + } + if (this.#plain) + return this.#plain; + const state = this.#sim.state(); + this.#sim.add(state, this.#start, 0, true); + return (this.#plain = this.#intern(this.#sim.done(state))); + } + // the next state, after a miss in `d.ascii` + next(d, c) { + const code = c.charCodeAt(0); + const found = code < 128 ? undefined : d.next.get(c); + if (found) + return found; + // the dotfile start is not in the cache, so it is never shared + const n = d === this.#dotStart ? + this.#intern(this.#dotSim.step(d.state, c, 0, true)) + : this.#intern(this.#sim.step(d.state, c, 1, true)); + if (code < 128) { + if (!d.ascii) { + d.ascii = new Array(128); + this.#size += 128; + } + d.ascii[code] = n; + } + else { + d.next.set(c, n); + } + this.#size++; + return n; + } +} +// the nodes in order, if the graph is a single chain +const linear = (start) => { + const nodes = []; + for (let n = start; n.t !== 'match'; n = n.next) { + if (n.t === 'split' || n.t === 'neg') + return undefined; + nodes.push(n); + } + return nodes; +}; +// Match a chain of nodes. Each node other than `*` matches exactly +// one char, so on a failure it is enough to go back to the last `*` +// and let it match one more char. This takes at most +// nodes.length * chars.length steps. +const testLinear = (nodes, chars, start, end) => { + let ni = 0; + let ci = start; + let starNi = -1; + let starCi = 0; + while (ci < end) { + const n = nodes[ni]; + if (n?.t === 'star') { + starNi = ni++; + starCi = ci; + continue; + } + const c = chars[ci]; + if (n && + (n.t === 'any' || + (n.t === 'lit' && litMatch(n, c)) || + (n.t === 'class' && n.re.test(c)))) { + ni++; + ci++; + continue; + } + if (starNi === -1) + return false; + ni = starNi + 1; + ci = ++starCi; + } + while (nodes[ni]?.t === 'star') + ni++; + return ni === nodes.length; +}; +// The least and most chars that the items can match. These are only +// bounds: a negation can match a string of any length, so it counts +// as 0 to Infinity. +const lengths = (items) => { + let min = 0; + let max = 0; + for (const it of items) { + const [lo, hi] = itemLengths(it); + min += lo; + max += hi; + } + return [min, max]; +}; +const itemLengths = (it) => { + if (it.t === 'star') + return [0, Infinity]; + if (it.t !== 'ext') + return [1, 1]; + if (it.type === '!') + return [0, Infinity]; + const alts = it.alts.map(lengths); + const min = Math.min(...alts.map(a => a[0])); + const max = Math.max(...alts.map(a => a[1])); + // a loop of alternatives that only match the empty string is empty + const loop = max === 0 ? 0 : Infinity; + return (it.type === '@' ? [min, max] + : it.type === '?' ? [0, max] + : it.type === '*' ? [0, loop] + : [min, loop]); +}; +// true if the chars from `start` match the literals +const hasAffix = (lits, chars, start) => { + for (let j = 0; j < lits.length; j++) { + if (!litMatch(lits[j], chars[start + j])) + return false; + } + return true; +}; +// a `/`, or half of a surrogate pair +const slashOrSurrogate = /[/\ud800-\udfff]/; +const surrogate = /[\ud800-\udfff]/; +// a string can be indexed by code point, unless it has surrogate +// pairs +const codePoints = (s) => surrogate.test(s) ? [...s] : s; +const noSlash = (s) => { + if (s.includes('/')) { + throw new Error('can only match a single path portion, got: ' + s); + } +}; +class Matcher { + pattern; + options; + #start; + // the number of node ids + #size; + #marks; + // the Sim for strings that are only `.` or `..` + #dotsSim; + // the string to compare, if the pattern has no magic. With + // `nocase:true`, the RegExp that folds case is made when it is + // first used. + #literal; + #literalFold = false; + #literalRe; + // the nodes between the prefix and suffix, if the graph is a + // single chain + #linear; + // the linear nodes are only `*` and `?`, so the length bounds and + // the prefix and suffix decide the match + #wild = false; + // the least and most chars that a match can have + #min = 0; + #max = Infinity; + // the literals that a match must start and end with. Each one + // matches exactly one char, and they are distinct items in the + // pattern, so a string that does not have them can not match. + #prefix = []; + #suffix = []; + // the prefix and suffix as strings, if they do not fold case + #prefixStr; + #suffixStr; + // there is a prefix or suffix to check + #affix = false; + #dfa; + #form; + constructor(pattern, options = {}) { + if (pattern.includes('/')) { + throw new Error('can only match a single path portion, got pattern: ' + pattern); + } + this.pattern = pattern; + this.options = options; + const { nocase = false, noext = false, normalize: n } = options; + this.#form = n === true ? 'NFC' : n || undefined; + // a pattern that is only an empty extglob is a literal string, + // except for `!()`, which matches any non-empty string + const literal = /^[?*+@]\(\)$/.test(pattern); + const toks = tokenize(pattern, nocase, noext || literal, this.#form, options.rangeMark); + let [items] = build(toks, pair(toks), 0, toks.length, true); + if (this.#form) + items = normalize(items, this.#form); + const [start, size] = compile(items, nocase); + this.#start = start; + this.#size = size; + if (items.every(it => it.t === 'lit')) { + this.#literal = items.map(it => it.ch).join(''); + this.#literalFold = nocase; + } + else { + const lit = (it) => it.t !== 'lit' ? undefined + : nocase ? { ch: it.ch, re: foldRe(it.ch) } + : { ch: it.ch }; + for (const it of items) { + const l = lit(it); + if (!l) + break; + this.#prefix.push(l); + } + for (let j = items.length - 1; j >= 0; j--) { + const l = lit(items[j]); + if (!l) + break; + this.#suffix.unshift(l); + } + this.#affix = !!(this.#prefix.length || this.#suffix.length); + if (!nocase) { + this.#prefixStr = this.#prefix.map(l => l.ch).join(''); + this.#suffixStr = this.#suffix.map(l => l.ch).join(''); + } + this.#linear = linear(this.#start)?.slice(this.#prefix.length, -this.#suffix.length || undefined); + this.#wild = !!this.#linear?.every(n => n.t === 'star' || n.t === 'any'); + const [min, max] = lengths(items); + this.#min = min; + this.#max = max; + } + } + test(s) { + // The `/` check uses the string as given, so with normalization it + // is a separate step. Otherwise, one scan finds both a `/` and the + // surrogate pairs that stop the string being indexed by code point. + if (this.#form) { + noSlash(s); + return this.#test(s.normalize(this.#form)); + } + if (slashOrSurrogate.test(s)) { + noSlash(s); + return this.#test(s, [...s]); + } + return this.#test(s, s); + } + /** + * The same as {@link Matcher#test}, but the string is not checked + * for `/` chars, so the result for a string that has one is not + * defined. Only use it for a string that is known to be one path + * portion, such as a part of a path that was split on `/`. It can + * be faster, because some patterns do not need to look at each char + * of the string. + */ + testUnchecked(s) { + return this.#test(this.#form ? s.normalize(this.#form) : s); + } + // Test a string that has no `/`. `chars` indexes it by code point. + // If it is not given, it is only found if a step needs it. + #test(s, chars) { + if (this.#literal !== undefined) { + return this.#literalFold ? + (this.#literalRe ??= newFoldRe(this.#literal)).test(s) + : s === this.#literal; + } + // the length check means that the prefix and suffix do not + // overlap. Without the chars, the length in code points is from + // half of the UTF-16 length (if each one is a surrogate pair) to + // all of it, which is often enough to know. + const min = this.#min; + const max = this.#max; + if (chars === undefined) { + const most = s.length; + const least = (most + 1) >> 1; + if (most < min || least > max) + return false; + if (least < min || most > max) + chars = codePoints(s); + } + if (chars !== undefined && + (chars.length < min || chars.length > max)) { + return false; + } + const prefix = this.#prefix.length; + if (this.#affix) { + if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) { + if (!s.startsWith(this.#prefixStr) || + !s.endsWith(this.#suffixStr)) { + return false; + } + } + else { + chars ??= codePoints(s); + const end = chars.length - this.#suffix.length; + if (!hasAffix(this.#prefix, chars, 0) || + !hasAffix(this.#suffix, chars, end)) { + return false; + } + } + } + const dotStart = !this.options.dot && s.startsWith('.'); + if (this.#linear) { + // `.` and `..` only match literal dots, even with `dot:true` + if (s === '.' || s === '..') + return false; + // only a literal can match the leading dot. A `*` can not + // start a dotfile, even if it matches nothing. + if (dotStart && !prefix) + return false; + if (this.#wild) + return true; + chars ??= codePoints(s); + const end = chars.length - this.#suffix.length; + return testLinear(this.#linear, chars, prefix, end); + } + chars ??= codePoints(s); + if (s === '.' || s === '..') { + this.#marks ??= marks(this.#size); + const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks)); + const start = sim.state(); + sim.add(start, this.#start, 0, true); + let state = sim.done(start); + for (let i = 0; i < chars.length; i++) { + state = sim.step(state, chars[i], i, true); + } + return state.match; + } + this.#marks ??= marks(this.#size); + const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks)); + let d = dfa.start(dotStart); + // read char codes from the string, so that a one-char string is + // only made for a cache miss + const str = chars === s; + for (let i = 0; i < chars.length; i++) { + if (d.dead) + return false; + const code = str ? s.charCodeAt(i) : chars[i].charCodeAt(0); + d = d.ascii?.[code] ?? dfa.next(d, chars[i]); + } + return d.match; + } + /** a readable listing of the state machine */ + toString() { + return show(this.#start); + } +} +exports.Matcher = Matcher; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.js.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5aa9533229e84fd54bd1a84bffb09cb76194a5bf --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,yDAAiD;AACjD,qDAAwD;AAkDxD,sDAAsD;AACtD,MAAM,KAAK,GAAS,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,EAAE,CAAA;AAEzC,MAAM,QAAQ,GAAG,OAAO,CAAA;AAExB,MAAM,GAAG,GAAG,CAAC,EAAU,EAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAA;AAEpD,MAAM,QAAQ,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,s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YACtC,IAAI,CAAC,CAAC,IAAI;gBAAE,OAAO,KAAK,CAAA;YACxB,MAAM,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;YAC5D,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAE,CAAC,CAAA;QAC/C,CAAC;QACD,OAAO,CAAC,CAAC,KAAK,CAAA;IAChB,CAAC;IAED,8CAA8C;IAC9C,QAAQ;QACN,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IAC1B,CAAC;CACF;AArND,0BAqNC","sourcesContent":["import { numericRange } from './numeric-range.js'\nimport { type Form, parseClass } from './parse-class.js'\n\nexport type { Form }\n\nexport type MatcherOptions = {\n /** perform a case-insensitive match */\n nocase?: boolean\n /** do not treat strings starting with `.` specially */\n dot?: boolean\n /** do not match extglobs (treat them as normal strings) */\n noext?: boolean\n /**\n * normalize unicode in the pattern and the tested strings, with\n * this form. `true` means `'NFC'`.\n */\n normalize?: boolean | Form\n /**\n * A char that marks a numeric range in the pattern, as\n * `..`, where `lo` and `hi` are integers. It\n * matches the strings that the bash brace expansion `{..}`\n * makes, such as `{1..100}` or `{001..100}`, without making each\n * one. A mark is never escaped by a `\\` before it. Inside a `[...]`\n * class, a mark is a char of the class.\n */\n rangeMark?: string\n}\n\n// parsed pattern items\nexport type Item =\n | { t: 'lit'; ch: string }\n | { t: 'any' | 'star' }\n | { t: 'class'; re: RegExp }\n | { t: 'ext'; type: string; alts: Item[][] }\n\n// extglob syntax tokens become literals if they are not part of a\n// closed extglob\nexport type Token =\n Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' }\n\n// state machine nodes\nexport type NegNode = { t: 'neg'; id: number; sub: Node; next: Node }\nexport type SplitNode = { t: 'split'; id: number; out: Node[] }\nexport type Node =\n | ({ t: 'lit'; id: number; next: Node } & Lit)\n | { t: 'any' | 'star'; id: number; next: Node }\n | { t: 'class'; id: number; re: RegExp; next: Node }\n | SplitNode\n | NegNode\n | { t: 'match'; id: number }\n\n// the end of the pattern, or of a negated sub-pattern\nconst MATCH: Node = { t: 'match', id: 0 }\n\nconst extTypes = '!?+*@'\n\nconst lit = (ch: string): Item => ({ t: 'lit', ch })\n\nconst reEscape = (s: string) => s.replace(/[\\\\^$.*+?()[\\]{}|/]/g, '\\\\$&')\n\n// a RegExp that only matches `s`, with unicode case folding\nconst newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu')\n\n// foldRe for one literal char. The same chars are in most patterns,\n// so keep them. A RegExp without the `g` or `y` flag has no state to\n// share.\nconst foldCache = new Map()\nconst foldRe = (ch: string) => {\n let re = foldCache.get(ch)\n if (!re) {\n re = newFoldRe(ch)\n if (foldCache.size >= 1000) foldCache.clear()\n foldCache.set(ch, re)\n }\n return re\n}\n\n/**\n * A literal char. With `nocase:true`, `re` folds case, and `ascii`\n * holds its results for ASCII chars, by char code: 1 for a match,\n * and 2 for not.\n */\nexport type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array }\n\nconst litMatch = (l: Lit, c: string) => {\n if (c === l.ch) return true\n if (!l.re) return false\n const code = c.charCodeAt(0)\n if (code >= 128) return l.re.test(c)\n const ascii = (l.ascii ??= new Uint8Array(128))\n ascii[code] ||= l.re.test(c) ? 1 : 2\n return ascii[code] === 1\n}\n\nconst tokenize = (\n p: string,\n nocase: boolean,\n noext: boolean,\n form?: Form,\n mark?: string,\n) => {\n const toks: Token[] = []\n for (let i = 0; i < p.length;) {\n const c = String.fromCodePoint(p.codePointAt(i)!)\n if (mark) {\n // a \\ before a range would only escape its first char\n const m = c === '\\\\' && p.startsWith(mark, i + 1) ? 1 : 0\n if (m || c === mark) {\n const start = i + m + mark.length\n const end = p.indexOf(mark, start)\n const r = /^(-?\\d+)\\.\\.(-?\\d+)$/.exec(p.slice(start, end))\n const alts = end !== -1 && r && numericRange(r[1]!, r[2]!)\n if (alts) {\n toks.push({ t: 'ext', type: '@', alts })\n i = end + mark.length\n continue\n }\n }\n }\n if (c === '\\\\') {\n // a trailing \\ is a literal \\\n const e = p.codePointAt(i + 1)\n const ch = e === undefined ? c : String.fromCodePoint(e)\n toks.push(lit(ch))\n i += 1 + ch.length\n continue\n }\n if (c === '[') {\n const [re, consumed] = parseClass(p, i, nocase, form)\n if (consumed) {\n toks.push({ t: 'class', re })\n i += consumed\n continue\n }\n }\n if (!noext && extTypes.includes(c) && p[i + 1] === '(') {\n toks.push({ t: 'open', type: c })\n i += 2\n continue\n }\n toks.push(\n !noext && c === '|' ? { t: 'bar' }\n : !noext && c === ')' ? { t: 'close' }\n : c === '*' ? { t: 'star' }\n : c === '?' ? { t: 'any' }\n : lit(c),\n )\n i += c.length\n }\n return toks\n}\n\n// map each open token index to the index of its close token\nconst pair = (toks: Token[]) => {\n const pairs = new Map()\n const stack: number[] = []\n toks.forEach((tok, i) => {\n if (tok.t === 'open') stack.push(i)\n else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i)\n })\n return pairs\n}\n\n// build the alternatives between start and end. An open token that\n// is not closed is never inside a closed extglob, so bar and close\n// tokens are only literal at the top level.\nconst build = (\n toks: Token[],\n pairs: Map,\n start: number,\n end: number,\n top: boolean,\n): Item[][] => {\n let seq: Item[] = []\n const alts = [seq]\n for (let i = start; i < end; i++) {\n const tok = toks[i]!\n const close = pairs.get(i)\n if (tok.t === 'open' && close !== undefined) {\n const sub = build(toks, pairs, i + 1, close, false)\n seq.push({ t: 'ext', type: tok.type, alts: sub })\n i = close\n } else if (tok.t === 'bar' && !top) {\n alts.push((seq = []))\n } else if (tok.t === 'open') {\n seq.push(lit(tok.type), lit('('))\n } else if (tok.t === 'bar') {\n seq.push(lit('|'))\n } else if (tok.t === 'close') {\n seq.push(lit(')'))\n } else {\n seq.push(tok)\n }\n }\n return alts\n}\n\n// normalize each run of literal chars as one string, so that a char\n// and the combining marks after it compose (or decompose) together.\n// Syntax is already parsed, so a char that normalizes to a syntax\n// char (such as full-width `*` in NFKC) stays a literal.\nconst normalize = (items: Item[], form: Form): Item[] => {\n const out: Item[] = []\n let run = ''\n const flush = () => {\n for (const ch of run.normalize(form)) out.push(lit(ch))\n run = ''\n }\n for (const it of items) {\n if (it.t === 'lit') {\n run += it.ch\n continue\n }\n flush()\n out.push(\n it.t === 'ext' ?\n { ...it, alts: it.alts.map(a => normalize(a, form)) }\n : it,\n )\n }\n flush()\n return out\n}\n\n// the start node, and the number of node ids. Ids are dense, from 0\n// for the match node.\nconst compile = (\n items: Item[],\n nocase: boolean,\n): [start: Node, size: number] => {\n let id = 1\n const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out })\n const seq = (items: Item[], next: Node): Node =>\n items.reduceRight((next, it) => item(it, next), next)\n const item = (it: Item, next: Node): Node => {\n switch (it.t) {\n case 'lit':\n const re = nocase ? foldRe(it.ch) : undefined\n return { t: 'lit', id: id++, ch: it.ch, re, next }\n case 'any':\n case 'star':\n return { t: it.t, id: id++, next }\n case 'class':\n return { t: 'class', id: id++, re: it.re, next }\n }\n const alts = (next: Node) => it.alts.map(a => seq(a, next))\n switch (it.type) {\n case '@':\n return split(alts(next))\n case '?':\n return split([next, ...alts(next)])\n case '!':\n return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }\n }\n // * and +, loop back after each match\n const after = split([])\n const entry = split(alts(after))\n after.out.push(next, entry)\n return it.type === '*' ? after : entry\n }\n const start = seq(items, MATCH)\n return [start, id]\n}\n\n// one line per node, in the order that a walk from the start\n// reaches them. Edges point to node ids. The nodes of a negated\n// sub-pattern are indented under their negation.\nconst show = (start: Node): string => {\n const lines: string[] = []\n const seen = new Set()\n const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id))\n const walk = (n: Node, indent: string) => {\n if (n.t === 'match' || seen.has(n)) return\n seen.add(n)\n const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`)\n switch (n.t) {\n case 'split':\n line(`split -> ${n.out.map(ref).join(', ')}`)\n for (const o of n.out) walk(o, indent)\n return\n case 'neg':\n line(`!(${ref(n.sub)}) -> ${ref(n.next)}`)\n walk(n.sub, indent + ' ')\n return walk(n.next, indent)\n case 'lit':\n line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`)\n break\n case 'class':\n line(`${n.re} -> ${ref(n.next)}`)\n break\n default:\n line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`)\n }\n walk(n.next, indent)\n }\n walk(start, '')\n return [`start -> ${ref(start)}`, ...lines].join('\\n')\n}\n\n// A thread inside a !(...) negation. It holds the threads of the\n// negated sub-pattern, started where the negation started. The\n// negation matches the chars so far if the sub-pattern does not.\ntype Run = { t: 'run'; neg: NegNode; state: State }\n\n// The threads at one position in the string. Each node thread is\n// only kept once, and runs with the same state are only kept once,\n// so that identical threads merge. The match node is not in\n// `threads`, because it can not step. It sets `match` instead.\nclass State {\n // set by the Sim, to mark the nodes that this state has\n gen: number\n threads: Node[] = []\n match = false\n runs: Run[] = []\n // the sorted ids of the threads, with 0 for a match, once the\n // state is done\n ids: number[] = []\n\n constructor(gen: number) {\n this.gen = gen\n }\n\n // no threads, so nothing more can match\n get dead() {\n return !this.threads.length && !this.match && !this.runs.length\n }\n}\n\n// true if the two states hold the same threads\nconst sameState = (a: State, b: State): boolean => {\n if (a.ids.length !== b.ids.length) return false\n if (a.runs.length !== b.runs.length) return false\n if (a.ids.some((id, i) => id !== b.ids[i])) return false\n return a.runs.every(r =>\n b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)),\n )\n}\n\n/**\n * For each node id, the gen of the last state that has the node as\n * a thread, and of the last state that walked through it. A state is\n * built to the end before the states around it go on, and the nodes\n * of a negated sub-pattern are only in its states (other than the\n * match node, which is never marked). So one mark for each node is\n * enough to know if the state being built has it. The Sims of a\n * matcher never run at the same time, so they share one Marks.\n */\nexport type Marks = { has: Float64Array; seen: Float64Array; gen: number }\n\nconst marks = (size: number): Marks => ({\n has: new Float64Array(size),\n seen: new Float64Array(size),\n gen: 0,\n})\n\nclass Sim {\n // `.` and `..` only match literal dots, even with `dot:true`\n dots: boolean\n // the string starts with `.`, and `dot:true` is not set\n dotStart: boolean\n #marks: Marks\n\n constructor(dots: boolean, dotStart: boolean, marks: Marks) {\n this.dots = dots\n this.dotStart = dotStart\n this.#marks = marks\n }\n\n state() {\n return new State(++this.#marks.gen)\n }\n\n // sort the ids of a state, once it has all of its threads\n done(state: State) {\n state.ids = state.threads.map(n => n.id).sort((a, b) => a - b)\n if (state.match) state.ids.unshift(MATCH.id)\n return state\n }\n\n // true the first time that the state walks through the node, so\n // that loops in the graph stop\n #visit(state: State, node: Node) {\n const { seen } = this.#marks\n if (seen[node.id] === state.gen) return false\n seen[node.id] = state.gen\n return true\n }\n\n #addThread(state: State, node: Node) {\n const { has } = this.#marks\n if (has[node.id] === state.gen) return false\n has[node.id] = state.gen\n state.threads.push(node)\n return true\n }\n\n // wildcards only match a leading dot if `dot:true`. In a negated\n // sub-pattern, this does not apply, because the negation itself\n // can not match a leading dot.\n restricted(i: number, top: boolean) {\n return top && (this.dots || (this.dotStart && i === 0))\n }\n\n add(state: State, node: Node, i: number, top: boolean): void {\n switch (node.t) {\n case 'split':\n if (!this.#visit(state, node)) return\n for (const o of node.out) this.add(state, o, i, top)\n return\n case 'neg':\n if (!this.#visit(state, node)) return\n const sub = this.state()\n this.add(sub, node.sub, i, false)\n this.done(sub)\n return this.addRun(\n state,\n { t: 'run', neg: node, state: sub },\n i,\n top,\n )\n case 'star':\n // a * can not start a dotfile, even if it matches nothing\n if (this.restricted(i, top)) return\n if (this.#addThread(state, node))\n this.add(state, node.next, i, top)\n return\n case 'match':\n state.match = true\n return\n default:\n this.#addThread(state, node)\n }\n }\n\n addRun(state: State, run: Run, i: number, top: boolean) {\n for (const r of state.runs) {\n if (r.neg === run.neg && sameState(r.state, run.state)) return\n }\n state.runs.push(run)\n if (!run.state.match) {\n this.add(state, run.neg.next, i, top)\n }\n }\n\n // the threads after char `c`, at index `i`\n step(state: State, c: string, i: number, top: boolean): State {\n const next = this.state()\n for (const th of state.threads) {\n switch (th.t) {\n case 'lit':\n if (litMatch(th, c)) {\n this.add(next, th.next, i + 1, top)\n }\n break\n case 'any':\n if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top)\n break\n case 'class':\n if (!this.restricted(i, top) && th.re.test(c)) {\n this.add(next, th.next, i + 1, top)\n }\n break\n case 'star':\n if (!this.restricted(i, top)) this.add(next, th, i + 1, top)\n }\n }\n if (!this.restricted(i, top)) {\n for (const run of state.runs) {\n // a sub-pattern with no threads can not match again, so the\n // run stays the same\n if (run.state.dead) {\n this.addRun(next, run, i + 1, top)\n continue\n }\n const sub = this.step(run.state, c, i, false)\n this.addRun(\n next,\n { t: 'run', neg: run.neg, state: sub },\n i + 1,\n top,\n )\n }\n }\n return this.done(next)\n }\n}\n\n// A canonical key for the threads in a state. States with the same\n// key hold the same threads, so they match the same strings.\nconst stateKey = (state: State): string => {\n const ids = state.ids.join()\n if (!state.runs.length) return ids\n const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`)\n return `${ids}|${runs.sort().join('|')}`\n}\n\n// A cached state of the simulation, and the states that each char\n// leads to.\ntype DState = {\n state: State\n match: boolean\n // no threads, so nothing more can match\n dead: boolean\n // the next state for each ASCII char, by char code, and for the\n // other chars\n ascii?: (DState | undefined)[]\n next: Map\n}\n\n// The cache can hold about this many chars of state keys and\n// transitions. When it is full, it is cleared, so that a pattern\n// can not use an unbounded amount of memory.\nconst DFA_BUDGET = 1 << 18\n\n// A cache of the states that the simulation reaches, built as the\n// matcher is used. Each char of a string is then one Map lookup,\n// once the states that it leads to are known.\n//\n// The dot rules only restrict the first char of a dotfile (strings\n// that are only `.` or `..` do not use the cache). So a dotfile\n// starts at its own state, which takes its first step with the\n// restriction, and every other state takes steps without it.\nclass Dfa {\n #start: Node\n #states = new Map()\n #size = 0\n #plain?: DState\n #dotStart?: DState\n #sim: Sim\n #dotSim: Sim\n\n constructor(start: Node, marks: Marks) {\n this.#start = start\n this.#sim = new Sim(false, false, marks)\n this.#dotSim = new Sim(false, true, marks)\n }\n\n #make(state: State): DState {\n return {\n state,\n match: state.match,\n dead: state.dead,\n next: new Map(),\n }\n }\n\n #intern(state: State): DState {\n const key = stateKey(state)\n const found = this.#states.get(key)\n if (found) return found\n if (this.#size > DFA_BUDGET) this.#clear()\n const d = this.#make(state)\n this.#states.set(key, d)\n this.#size += key.length + 1\n return d\n }\n\n #clear() {\n this.#states.clear()\n this.#size = 0\n this.#plain = undefined\n this.#dotStart = undefined\n }\n\n start(dotStart: boolean): DState {\n if (dotStart) {\n if (this.#dotStart) return this.#dotStart\n const state = this.#dotSim.state()\n this.#dotSim.add(state, this.#start, 0, true)\n return (this.#dotStart = this.#make(this.#dotSim.done(state)))\n }\n if (this.#plain) return this.#plain\n const state = this.#sim.state()\n this.#sim.add(state, this.#start, 0, true)\n return (this.#plain = this.#intern(this.#sim.done(state)))\n }\n\n // the next state, after a miss in `d.ascii`\n next(d: DState, c: string): DState {\n const code = c.charCodeAt(0)\n const found = code < 128 ? undefined : d.next.get(c)\n if (found) return found\n // the dotfile start is not in the cache, so it is never shared\n const n =\n d === this.#dotStart ?\n this.#intern(this.#dotSim.step(d.state, c, 0, true))\n : this.#intern(this.#sim.step(d.state, c, 1, true))\n if (code < 128) {\n if (!d.ascii) {\n d.ascii = new Array(128)\n this.#size += 128\n }\n d.ascii[code] = n\n } else {\n d.next.set(c, n)\n }\n this.#size++\n return n\n }\n}\n\n/**\n * A node in a graph with no splits or negations. Such a graph is a\n * chain of nodes that each match one char, or a `*`.\n */\nexport type LinearNode = Exclude<\n Node,\n SplitNode | NegNode | { t: 'match' }\n>\n\n// the nodes in order, if the graph is a single chain\nconst linear = (start: Node): LinearNode[] | undefined => {\n const nodes: LinearNode[] = []\n for (let n = start; n.t !== 'match'; n = n.next) {\n if (n.t === 'split' || n.t === 'neg') return undefined\n nodes.push(n)\n }\n return nodes\n}\n\n// Match a chain of nodes. Each node other than `*` matches exactly\n// one char, so on a failure it is enough to go back to the last `*`\n// and let it match one more char. This takes at most\n// nodes.length * chars.length steps.\nconst testLinear = (\n nodes: LinearNode[],\n chars: ArrayLike,\n start: number,\n end: number,\n) => {\n let ni = 0\n let ci = start\n let starNi = -1\n let starCi = 0\n while (ci < end) {\n const n = nodes[ni]\n if (n?.t === 'star') {\n starNi = ni++\n starCi = ci\n continue\n }\n const c = chars[ci]!\n if (\n n &&\n (n.t === 'any' ||\n (n.t === 'lit' && litMatch(n, c)) ||\n (n.t === 'class' && n.re.test(c)))\n ) {\n ni++\n ci++\n continue\n }\n if (starNi === -1) return false\n ni = starNi + 1\n ci = ++starCi\n }\n while (nodes[ni]?.t === 'star') ni++\n return ni === nodes.length\n}\n\n// The least and most chars that the items can match. These are only\n// bounds: a negation can match a string of any length, so it counts\n// as 0 to Infinity.\nconst lengths = (items: Item[]): [min: number, max: number] => {\n let min = 0\n let max = 0\n for (const it of items) {\n const [lo, hi] = itemLengths(it)\n min += lo\n max += hi\n }\n return [min, max]\n}\n\nconst itemLengths = (it: Item): [min: number, max: number] => {\n if (it.t === 'star') return [0, Infinity]\n if (it.t !== 'ext') return [1, 1]\n if (it.type === '!') return [0, Infinity]\n const alts = it.alts.map(lengths)\n const min = Math.min(...alts.map(a => a[0]))\n const max = Math.max(...alts.map(a => a[1]))\n // a loop of alternatives that only match the empty string is empty\n const loop = max === 0 ? 0 : Infinity\n return (\n it.type === '@' ? [min, max]\n : it.type === '?' ? [0, max]\n : it.type === '*' ? [0, loop]\n : [min, loop]\n )\n}\n\n// true if the chars from `start` match the literals\nconst hasAffix = (\n lits: Lit[],\n chars: ArrayLike,\n start: number,\n) => {\n for (let j = 0; j < lits.length; j++) {\n if (!litMatch(lits[j]!, chars[start + j]!)) return false\n }\n return true\n}\n\n// a `/`, or half of a surrogate pair\nconst slashOrSurrogate = /[/\\ud800-\\udfff]/\nconst surrogate = /[\\ud800-\\udfff]/\n\n// a string can be indexed by code point, unless it has surrogate\n// pairs\nconst codePoints = (s: string): ArrayLike =>\n surrogate.test(s) ? [...s] : s\n\nconst noSlash = (s: string) => {\n if (s.includes('/')) {\n throw new Error('can only match a single path portion, got: ' + s)\n }\n}\n\nexport class Matcher {\n pattern: string\n options: MatcherOptions\n #start: Node\n // the number of node ids\n #size: number\n #marks?: Marks\n // the Sim for strings that are only `.` or `..`\n #dotsSim?: Sim\n // the string to compare, if the pattern has no magic. With\n // `nocase:true`, the RegExp that folds case is made when it is\n // first used.\n #literal?: string\n #literalFold = false\n #literalRe?: RegExp\n // the nodes between the prefix and suffix, if the graph is a\n // single chain\n #linear?: LinearNode[]\n // the linear nodes are only `*` and `?`, so the length bounds and\n // the prefix and suffix decide the match\n #wild = false\n // the least and most chars that a match can have\n #min = 0\n #max = Infinity\n // the literals that a match must start and end with. Each one\n // matches exactly one char, and they are distinct items in the\n // pattern, so a string that does not have them can not match.\n #prefix: Lit[] = []\n #suffix: Lit[] = []\n // the prefix and suffix as strings, if they do not fold case\n #prefixStr?: string\n #suffixStr?: string\n // there is a prefix or suffix to check\n #affix = false\n #dfa?: Dfa\n #form?: Form\n\n constructor(pattern: string, options: MatcherOptions = {}) {\n if (pattern.includes('/')) {\n throw new Error(\n 'can only match a single path portion, got pattern: ' + pattern,\n )\n }\n this.pattern = pattern\n this.options = options\n const { nocase = false, noext = false, normalize: n } = options\n this.#form = n === true ? 'NFC' : n || undefined\n // a pattern that is only an empty extglob is a literal string,\n // except for `!()`, which matches any non-empty string\n const literal = /^[?*+@]\\(\\)$/.test(pattern)\n const toks = tokenize(\n pattern,\n nocase,\n noext || literal,\n this.#form,\n options.rangeMark,\n )\n let [items] = build(toks, pair(toks), 0, toks.length, true)\n if (this.#form) items = normalize(items!, this.#form)\n const [start, size] = compile(items!, nocase)\n this.#start = start\n this.#size = size\n if (items!.every(it => it.t === 'lit')) {\n this.#literal = items!.map(it => it.ch).join('')\n this.#literalFold = nocase\n } else {\n const lit = (it: Item): Lit | undefined =>\n it.t !== 'lit' ? undefined\n : nocase ? { ch: it.ch, re: foldRe(it.ch) }\n : { ch: it.ch }\n for (const it of items!) {\n const l = lit(it)\n if (!l) break\n this.#prefix.push(l)\n }\n for (let j = items!.length - 1; j >= 0; j--) {\n const l = lit(items![j]!)\n if (!l) break\n this.#suffix.unshift(l)\n }\n this.#affix = !!(this.#prefix.length || this.#suffix.length)\n if (!nocase) {\n this.#prefixStr = this.#prefix.map(l => l.ch).join('')\n this.#suffixStr = this.#suffix.map(l => l.ch).join('')\n }\n this.#linear = linear(this.#start)?.slice(\n this.#prefix.length,\n -this.#suffix.length || undefined,\n )\n this.#wild = !!this.#linear?.every(\n n => n.t === 'star' || n.t === 'any',\n )\n const [min, max] = lengths(items!)\n this.#min = min\n this.#max = max\n }\n }\n\n test(s: string): boolean {\n // The `/` check uses the string as given, so with normalization it\n // is a separate step. Otherwise, one scan finds both a `/` and the\n // surrogate pairs that stop the string being indexed by code point.\n if (this.#form) {\n noSlash(s)\n return this.#test(s.normalize(this.#form))\n }\n if (slashOrSurrogate.test(s)) {\n noSlash(s)\n return this.#test(s, [...s])\n }\n return this.#test(s, s)\n }\n\n /**\n * The same as {@link Matcher#test}, but the string is not checked\n * for `/` chars, so the result for a string that has one is not\n * defined. Only use it for a string that is known to be one path\n * portion, such as a part of a path that was split on `/`. It can\n * be faster, because some patterns do not need to look at each char\n * of the string.\n */\n testUnchecked(s: string): boolean {\n return this.#test(this.#form ? s.normalize(this.#form) : s)\n }\n\n // Test a string that has no `/`. `chars` indexes it by code point.\n // If it is not given, it is only found if a step needs it.\n #test(s: string, chars?: ArrayLike): boolean {\n if (this.#literal !== undefined) {\n return this.#literalFold ?\n (this.#literalRe ??= newFoldRe(this.#literal)).test(s)\n : s === this.#literal\n }\n // the length check means that the prefix and suffix do not\n // overlap. Without the chars, the length in code points is from\n // half of the UTF-16 length (if each one is a surrogate pair) to\n // all of it, which is often enough to know.\n const min = this.#min\n const max = this.#max\n if (chars === undefined) {\n const most = s.length\n const least = (most + 1) >> 1\n if (most < min || least > max) return false\n if (least < min || most > max) chars = codePoints(s)\n }\n if (\n chars !== undefined &&\n (chars.length < min || chars.length > max)\n ) {\n return false\n }\n const prefix = this.#prefix.length\n if (this.#affix) {\n if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {\n if (\n !s.startsWith(this.#prefixStr) ||\n !s.endsWith(this.#suffixStr)\n ) {\n return false\n }\n } else {\n chars ??= codePoints(s)\n const end = chars.length - this.#suffix.length\n if (\n !hasAffix(this.#prefix, chars, 0) ||\n !hasAffix(this.#suffix, chars, end)\n ) {\n return false\n }\n }\n }\n const dotStart = !this.options.dot && s.startsWith('.')\n if (this.#linear) {\n // `.` and `..` only match literal dots, even with `dot:true`\n if (s === '.' || s === '..') return false\n // only a literal can match the leading dot. A `*` can not\n // start a dotfile, even if it matches nothing.\n if (dotStart && !prefix) return false\n if (this.#wild) return true\n chars ??= codePoints(s)\n const end = chars.length - this.#suffix.length\n return testLinear(this.#linear, chars, prefix, end)\n }\n chars ??= codePoints(s)\n if (s === '.' || s === '..') {\n this.#marks ??= marks(this.#size)\n const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks))\n const start = sim.state()\n sim.add(start, this.#start, 0, true)\n let state = sim.done(start)\n for (let i = 0; i < chars.length; i++) {\n state = sim.step(state, chars[i]!, i, true)\n }\n return state.match\n }\n this.#marks ??= marks(this.#size)\n const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks))\n let d = dfa.start(dotStart)\n // read char codes from the string, so that a one-char string is\n // only made for a cache miss\n const str = chars === s\n for (let i = 0; i < chars.length; i++) {\n if (d.dead) return false\n const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0)\n d = d.ascii?.[code] ?? dfa.next(d, chars[i]!)\n }\n return d.match\n }\n\n /** a readable listing of the state machine */\n toString(): string {\n return show(this.#start)\n }\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.min.js b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.min.js new file mode 100644 index 0000000000000000000000000000000000000000..1191f2a81995c8466e249e5b4dce8c298e7263b4 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/index.min.js @@ -0,0 +1,3 @@ +"use strict";var L=(n,t)=>()=>{try{return t||n((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}};var W=L(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.numericRange=void 0;var P=(n,t)=>n===t?{t:"lit",ch:String(n)}:{t:"class",re:new RegExp(`^[${n}-${t}]$`)},j=(n,t)=>t.map(e=>[P(n,n),...e]),w=(n,t)=>{if(!n)return[[]];let e=+n[0],s=+t[0],r=n.slice(1),i=t.slice(1);if(e===s)return j(e,w(r,i));let h="0".repeat(r.length),c="9".repeat(r.length),o=[];r!==h&&o.push(...j(e++,w(r,c)));let u=i===c?[]:j(s--,w(h,i));return e<=s&&o.push([P(e,s),...Array.from(r,()=>P(0,9))]),o.push(...u),o},O=(n,t,e)=>{if(e)return w(String(n).padStart(e,"0"),String(t).padStart(e,"0"));let s=[];for(let r=String(n).length;r<=String(t).length;r++){let i=Math.max(n,r===1?0:10**(r-1)),h=Math.min(t,10**r-1);s.push(...w(String(i),String(h)))}return s},X=(n,t)=>{let e=Number(n),s=Number(t);if(!Number.isSafeInteger(e)||!Number.isSafeInteger(s))return;e>s&&([e,s]=[s,e]);let i=/^-?0\d/.test(n)||/^-?0\d/.test(t)?Math.max(n.length,t.length):0,h=[];if(e<0){let c=O(Math.max(-s,1),-e,i&&i-1);h.push(...c.map(o=>[{t:"lit",ch:"-"},...o]))}return s>=0&&h.push(...O(Math.max(e,0),s,i)),h};A.numericRange=X});var I=L(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.parseClass=void 0;var Y={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},$=n=>n.replace(/[[\]\\-]/g,"\\$&"),R=/$./,tt=(n,t,e=!1,s)=>{let r=g=>{let m=s?g.normalize(s):g;return[...m].length===1?m:g},i=t;if(n.charAt(i)!=="[")throw new Error("not in a brace expression");let h=[],c=[],o=i+1,u=!1,a=!1,l=!1,d=i,p="";t:for(;op.codePointAt(0)?h.push($(p)+"-"+$(m)):m===p&&h.push($(m)),p="",o+=g.length;continue}if(n.startsWith("-]",o+g.length)){h.push($(m+"-")),o+=g.length+1;continue}if(n.startsWith("-",o+g.length)){p=m,o+=g.length+1;continue}h.push($(m)),o+=g.length}if(d({t:"lit",ch:n}),it=n=>n.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),Z=n=>new RegExp(`^${it(n)}$`,"iu"),M=new Map,B=n=>{let t=M.get(n);return t||(t=Z(n),M.size>=1e3&&M.clear(),M.set(n,t)),t},z=(n,t)=>{if(t===n.ch)return!0;if(!n.re)return!1;let e=t.charCodeAt(0);if(e>=128)return n.re.test(t);let s=n.ascii??=new Uint8Array(128);return s[e]||=n.re.test(t)?1:2,s[e]===1},rt=(n,t,e,s,r)=>{let i=[];for(let h=0;h{let t=new Map,e=[];return n.forEach((s,r)=>{s.t==="open"?e.push(r):s.t==="close"&&e.length&&t.set(e.pop(),r)}),t},D=(n,t,e,s,r)=>{let i=[],h=[i];for(let c=e;c{let e=[],s="",r=()=>{for(let i of s.normalize(t))e.push(y(i));s=""};for(let i of n){if(i.t==="lit"){s+=i.ch;continue}r(),e.push(i.t==="ext"?{...i,alts:i.alts.map(h=>G(h,t))}:i)}return r(),e},ht=(n,t)=>{let e=1,s=c=>({t:"split",id:e++,out:c}),r=(c,o)=>c.reduceRight((u,a)=>i(a,u),o),i=(c,o)=>{switch(c.t){case"lit":let d=t?B(c.ch):void 0;return{t:"lit",id:e++,ch:c.ch,re:d,next:o};case"any":case"star":return{t:c.t,id:e++,next:o};case"class":return{t:"class",id:e++,re:c.re,next:o}}let u=d=>c.alts.map(p=>r(p,d));switch(c.type){case"@":return s(u(o));case"?":return s([o,...u(o)]);case"!":return{t:"neg",id:e++,sub:s(u(k)),next:o}}let a=s([]),l=s(u(a));return a.out.push(o,l),c.type==="*"?a:l};return[r(n,k),e]},ct=n=>{let t=[],e=new Set,s=i=>i.t==="match"?"match":String(i.id),r=(i,h)=>{if(i.t==="match"||e.has(i))return;e.add(i);let c=o=>t.push(`${h}${i.id}: ${o}`);switch(i.t){case"split":c(`split -> ${i.out.map(s).join(", ")}`);for(let o of i.out)r(o,h);return;case"neg":return c(`!(${s(i.sub)}) -> ${s(i.next)}`),r(i.sub,h+" "),r(i.next,h);case"lit":c(`${JSON.stringify(i.ch)} -> ${s(i.next)}`);break;case"class":c(`${i.re} -> ${s(i.next)}`);break;default:c(`${i.t==="any"?"?":"*"} -> ${s(i.next)}`)}r(i.next,h)};return r(n,""),[`start -> ${s(n)}`,...t].join(` +`)},N=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(t){this.gen=t}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},H=(n,t)=>n.ids.length!==t.ids.length||n.runs.length!==t.runs.length||n.ids.some((e,s)=>e!==t.ids[s])?!1:n.runs.every(e=>t.runs.some(s=>s.neg===e.neg&&H(s.state,e.state))),q=n=>({has:new Float64Array(n),seen:new Float64Array(n),gen:0}),S=class{dots;dotStart;#t;constructor(t,e,s){this.dots=t,this.dotStart=e,this.#t=s}state(){return new N(++this.#t.gen)}done(t){return t.ids=t.threads.map(e=>e.id).sort((e,s)=>e-s),t.match&&t.ids.unshift(k.id),t}#s(t,e){let{seen:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,!0)}#e(t,e){let{has:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,t.threads.push(e),!0)}restricted(t,e){return e&&(this.dots||this.dotStart&&t===0)}add(t,e,s,r){switch(e.t){case"split":if(!this.#s(t,e))return;for(let h of e.out)this.add(t,h,s,r);return;case"neg":if(!this.#s(t,e))return;let i=this.state();return this.add(i,e.sub,s,!1),this.done(i),this.addRun(t,{t:"run",neg:e,state:i},s,r);case"star":if(this.restricted(s,r))return;this.#e(t,e)&&this.add(t,e.next,s,r);return;case"match":t.match=!0;return;default:this.#e(t,e)}}addRun(t,e,s,r){for(let i of t.runs)if(i.neg===e.neg&&H(i.state,e.state))return;t.runs.push(e),e.state.match||this.add(t,e.neg.next,s,r)}step(t,e,s,r){let i=this.state();for(let h of t.threads)switch(h.t){case"lit":z(h,e)&&this.add(i,h.next,s+1,r);break;case"any":this.restricted(s,r)||this.add(i,h.next,s+1,r);break;case"class":!this.restricted(s,r)&&h.re.test(e)&&this.add(i,h.next,s+1,r);break;case"star":this.restricted(s,r)||this.add(i,h,s+1,r)}if(!this.restricted(s,r))for(let h of t.runs){if(h.state.dead){this.addRun(i,h,s+1,r);continue}let c=this.step(h.state,e,s,!1);this.addRun(i,{t:"run",neg:h.neg,state:c},s+1,r)}return this.done(i)}},J=n=>{let t=n.ids.join();if(!n.runs.length)return t;let e=n.runs.map(s=>`${s.neg.id}(${J(s.state)})`);return`${t}|${e.sort().join("|")}`},at=1<<18,_=class{#t;#s=new Map;#e=0;#a;#n;#i;#o;constructor(t,e){this.#t=t,this.#i=new S(!1,!1,e),this.#o=new S(!1,!0,e)}#h(t){return{state:t,match:t.match,dead:t.dead,next:new Map}}#u(t){let e=J(t),s=this.#s.get(e);if(s)return s;this.#e>at&&this.#f();let r=this.#h(t);return this.#s.set(e,r),this.#e+=e.length+1,r}#f(){this.#s.clear(),this.#e=0,this.#a=void 0,this.#n=void 0}start(t){if(t){if(this.#n)return this.#n;let s=this.#o.state();return this.#o.add(s,this.#t,0,!0),this.#n=this.#h(this.#o.done(s))}if(this.#a)return this.#a;let e=this.#i.state();return this.#i.add(e,this.#t,0,!0),this.#a=this.#u(this.#i.done(e))}next(t,e){let s=e.charCodeAt(0),r=s<128?void 0:t.next.get(e);if(r)return r;let i=t===this.#n?this.#u(this.#o.step(t.state,e,0,!0)):this.#u(this.#i.step(t.state,e,1,!0));return s<128?(t.ascii||(t.ascii=new Array(128),this.#e+=128),t.ascii[s]=i):t.next.set(e,i),this.#e++,i}},ut=n=>{let t=[];for(let e=n;e.t!=="match";e=e.next){if(e.t==="split"||e.t==="neg")return;t.push(e)}return t},lt=(n,t,e,s)=>{let r=0,i=e,h=-1,c=0;for(;i{let t=0,e=0;for(let s of n){let[r,i]=ft(s);t+=r,e+=i}return[t,e]},ft=n=>{if(n.t==="star")return[0,1/0];if(n.t!=="ext")return[1,1];if(n.type==="!")return[0,1/0];let t=n.alts.map(K),e=Math.min(...t.map(i=>i[0])),s=Math.max(...t.map(i=>i[1])),r=s===0?0:1/0;return n.type==="@"?[e,s]:n.type==="?"?[0,s]:n.type==="*"?[0,r]:[e,r]},T=(n,t,e)=>{for(let s=0;spt.test(n)?[...n]:n,U=n=>{if(n.includes("/"))throw new Error("can only match a single path portion, got: "+n)},v=class{pattern;options;#t;#s;#e;#a;#n;#i=!1;#o;#h;#u=!1;#f=0;#m=1/0;#l=[];#c=[];#p;#g;#x=!1;#y;#r;constructor(t,e={}){if(t.includes("/"))throw new Error("can only match a single path portion, got pattern: "+t);this.pattern=t,this.options=e;let{nocase:s=!1,noext:r=!1,normalize:i}=e;this.#r=i===!0?"NFC":i||void 0;let h=/^[?*+@]\(\)$/.test(t),c=rt(t,s,r||h,this.#r,e.rangeMark),[o]=D(c,ot(c),0,c.length,!0);this.#r&&(o=G(o,this.#r));let[u,a]=ht(o,s);if(this.#t=u,this.#s=a,o.every(l=>l.t==="lit"))this.#n=o.map(l=>l.ch).join(""),this.#i=s;else{let l=f=>f.t!=="lit"?void 0:s?{ch:f.ch,re:B(f.ch)}:{ch:f.ch};for(let f of o){let x=l(f);if(!x)break;this.#l.push(x)}for(let f=o.length-1;f>=0;f--){let x=l(o[f]);if(!x)break;this.#c.unshift(x)}this.#x=!!(this.#l.length||this.#c.length),s||(this.#p=this.#l.map(f=>f.ch).join(""),this.#g=this.#c.map(f=>f.ch).join("")),this.#h=ut(this.#t)?.slice(this.#l.length,-this.#c.length||void 0),this.#u=!!this.#h?.every(f=>f.t==="star"||f.t==="any");let[d,p]=K(o);this.#f=d,this.#m=p}}test(t){return this.#r?(U(t),this.#d(t.normalize(this.#r))):dt.test(t)?(U(t),this.#d(t,[...t])):this.#d(t,t)}testUnchecked(t){return this.#d(this.#r?t.normalize(this.#r):t)}#d(t,e){if(this.#n!==void 0)return this.#i?(this.#o??=Z(this.#n)).test(t):t===this.#n;let s=this.#f,r=this.#m;if(e===void 0){let a=t.length,l=a+1>>1;if(ar)return!1;(lr)&&(e=b(t))}if(e!==void 0&&(e.lengthr))return!1;let i=this.#l.length;if(this.#x)if(this.#p!==void 0&&this.#g!==void 0){if(!t.startsWith(this.#p)||!t.endsWith(this.#g))return!1}else{e??=b(t);let a=e.length-this.#c.length;if(!T(this.#l,e,0)||!T(this.#c,e,a))return!1}let h=!this.options.dot&&t.startsWith(".");if(this.#h){if(t==="."||t===".."||h&&!i)return!1;if(this.#u)return!0;e??=b(t);let a=e.length-this.#c.length;return lt(this.#h,e,i,a)}if(e??=b(t),t==="."||t===".."){this.#e??=q(this.#s);let a=this.#a??=new S(!0,!1,this.#e),l=a.state();a.add(l,this.#t,0,!0);let d=a.done(l);for(let p=0;p\n a === b ?\n { t: 'lit', ch: String(a) }\n : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) }\n\nconst prefix = (d: number, alts: Item[][]) =>\n alts.map(s => [digit(d, d), ...s])\n\n// The digit strings from a to b, which have the same length.\nconst fixed = (a: string, b: string): Item[][] => {\n if (!a) return [[]]\n let lo = +a[0]!\n let hi = +b[0]!\n const ra = a.slice(1)\n const rb = b.slice(1)\n if (lo === hi) return prefix(lo, fixed(ra, rb))\n const zeros = '0'.repeat(ra.length)\n const nines = '9'.repeat(ra.length)\n const out: Item[][] = []\n if (ra !== zeros) out.push(...prefix(lo++, fixed(ra, nines)))\n const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb))\n if (lo <= hi) {\n out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))])\n }\n out.push(...last)\n return out\n}\n\n// The numbers from a to b, where 0 <= a <= b. If width is set, each\n// one has leading zeros to make it that many digits.\nconst nonneg = (a: number, b: number, width: number): Item[][] => {\n if (width) {\n return fixed(\n String(a).padStart(width, '0'),\n String(b).padStart(width, '0'),\n )\n }\n const out: Item[][] = []\n for (let len = String(a).length; len <= String(b).length; len++) {\n const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1))\n const hi = Math.min(b, 10 ** len - 1)\n out.push(...fixed(String(lo), String(hi)))\n }\n return out\n}\n\n/**\n * The strings that the bash brace expansion `{lo..hi}` makes, as\n * the alternatives of an `@(...)` extglob. Each one is a sequence of\n * digits and digit classes, so there are only a few of them, even for\n * a large range.\n *\n * If either end has a leading zero, such as `{01..10}`, each number\n * has leading zeros to make it as long as the longer end, counting a\n * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`.\n *\n * Returns undefined if either end is not a safe integer.\n */\nexport const numericRange = (\n loStr: string,\n hiStr: string,\n): Item[][] | undefined => {\n let lo = Number(loStr)\n let hi = Number(hiStr)\n if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) return\n if (lo > hi) [lo, hi] = [hi, lo]\n const padded = /^-?0\\d/.test(loStr) || /^-?0\\d/.test(hiStr)\n const width = padded ? Math.max(loStr.length, hiStr.length) : 0\n const out: Item[][] = []\n if (lo < 0) {\n const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1)\n out.push(...neg.map(s => [{ t: 'lit', ch: '-' } as Item, ...s]))\n }\n if (hi >= 0) out.push(...nonneg(Math.max(lo, 0), hi, width))\n return out\n}\n", "// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n '[:blank:]': ['\\\\p{Zs}\\\\t'],\n '[:cntrl:]': ['\\\\p{Cc}'],\n '[:digit:]': ['\\\\p{Nd}'],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n '[:lower:]': ['\\\\p{Ll}'],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n '[:upper:]': ['\\\\p{Lu}'],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n glob: string,\n position: number,\n nocase: boolean = false,\n form?: Form,\n): ParseClassResult => {\n // normalize one class member, if it stays one code point\n const norm = (c: string) => {\n const n = form ? c.normalize(form) : c\n return [...n].length === 1 ? n : c\n }\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = String.fromCodePoint(glob.codePointAt(i)!)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return [noMatch, glob.length - pos]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n const n = norm(c)\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n } else if (n === rangeStart) {\n ranges.push(braceEscape(n))\n }\n rangeStart = ''\n i += c.length\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + c.length)) {\n ranges.push(braceEscape(n + '-'))\n i += c.length + 1\n continue\n }\n if (glob.startsWith('-', i + c.length)) {\n rangeStart = n\n i += c.length + 1\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(n))\n i += c.length\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return [noMatch, 0]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return [noMatch, glob.length - pos]\n }\n\n const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n const comb =\n '^' +\n (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs)\n\n return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n", "import { numericRange } from './numeric-range.js'\nimport { type Form, parseClass } from './parse-class.js'\n\nexport type { Form }\n\nexport type MatcherOptions = {\n /** perform a case-insensitive match */\n nocase?: boolean\n /** do not treat strings starting with `.` specially */\n dot?: boolean\n /** do not match extglobs (treat them as normal strings) */\n noext?: boolean\n /**\n * normalize unicode in the pattern and the tested strings, with\n * this form. `true` means `'NFC'`.\n */\n normalize?: boolean | Form\n /**\n * A char that marks a numeric range in the pattern, as\n * `..`, where `lo` and `hi` are integers. It\n * matches the strings that the bash brace expansion `{..}`\n * makes, such as `{1..100}` or `{001..100}`, without making each\n * one. A mark is never escaped by a `\\` before it. Inside a `[...]`\n * class, a mark is a char of the class.\n */\n rangeMark?: string\n}\n\n// parsed pattern items\nexport type Item =\n | { t: 'lit'; ch: string }\n | { t: 'any' | 'star' }\n | { t: 'class'; re: RegExp }\n | { t: 'ext'; type: string; alts: Item[][] }\n\n// extglob syntax tokens become literals if they are not part of a\n// closed extglob\nexport type Token =\n Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' }\n\n// state machine nodes\nexport type NegNode = { t: 'neg'; id: number; sub: Node; next: Node }\nexport type SplitNode = { t: 'split'; id: number; out: Node[] }\nexport type Node =\n | ({ t: 'lit'; id: number; next: Node } & Lit)\n | { t: 'any' | 'star'; id: number; next: Node }\n | { t: 'class'; id: number; re: RegExp; next: Node }\n | SplitNode\n | NegNode\n | { t: 'match'; id: number }\n\n// the end of the pattern, or of a negated sub-pattern\nconst MATCH: Node = { t: 'match', id: 0 }\n\nconst extTypes = '!?+*@'\n\nconst lit = (ch: string): Item => ({ t: 'lit', ch })\n\nconst reEscape = (s: string) => s.replace(/[\\\\^$.*+?()[\\]{}|/]/g, '\\\\$&')\n\n// a RegExp that only matches `s`, with unicode case folding\nconst newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu')\n\n// foldRe for one literal char. The same chars are in most patterns,\n// so keep them. A RegExp without the `g` or `y` flag has no state to\n// share.\nconst foldCache = new Map()\nconst foldRe = (ch: string) => {\n let re = foldCache.get(ch)\n if (!re) {\n re = newFoldRe(ch)\n if (foldCache.size >= 1000) foldCache.clear()\n foldCache.set(ch, re)\n }\n return re\n}\n\n/**\n * A literal char. With `nocase:true`, `re` folds case, and `ascii`\n * holds its results for ASCII chars, by char code: 1 for a match,\n * and 2 for not.\n */\nexport type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array }\n\nconst litMatch = (l: Lit, c: string) => {\n if (c === l.ch) return true\n if (!l.re) return false\n const code = c.charCodeAt(0)\n if (code >= 128) return l.re.test(c)\n const ascii = (l.ascii ??= new Uint8Array(128))\n ascii[code] ||= l.re.test(c) ? 1 : 2\n return ascii[code] === 1\n}\n\nconst tokenize = (\n p: string,\n nocase: boolean,\n noext: boolean,\n form?: Form,\n mark?: string,\n) => {\n const toks: Token[] = []\n for (let i = 0; i < p.length;) {\n const c = String.fromCodePoint(p.codePointAt(i)!)\n if (mark) {\n // a \\ before a range would only escape its first char\n const m = c === '\\\\' && p.startsWith(mark, i + 1) ? 1 : 0\n if (m || c === mark) {\n const start = i + m + mark.length\n const end = p.indexOf(mark, start)\n const r = /^(-?\\d+)\\.\\.(-?\\d+)$/.exec(p.slice(start, end))\n const alts = end !== -1 && r && numericRange(r[1]!, r[2]!)\n if (alts) {\n toks.push({ t: 'ext', type: '@', alts })\n i = end + mark.length\n continue\n }\n }\n }\n if (c === '\\\\') {\n // a trailing \\ is a literal \\\n const e = p.codePointAt(i + 1)\n const ch = e === undefined ? c : String.fromCodePoint(e)\n toks.push(lit(ch))\n i += 1 + ch.length\n continue\n }\n if (c === '[') {\n const [re, consumed] = parseClass(p, i, nocase, form)\n if (consumed) {\n toks.push({ t: 'class', re })\n i += consumed\n continue\n }\n }\n if (!noext && extTypes.includes(c) && p[i + 1] === '(') {\n toks.push({ t: 'open', type: c })\n i += 2\n continue\n }\n toks.push(\n !noext && c === '|' ? { t: 'bar' }\n : !noext && c === ')' ? { t: 'close' }\n : c === '*' ? { t: 'star' }\n : c === '?' ? { t: 'any' }\n : lit(c),\n )\n i += c.length\n }\n return toks\n}\n\n// map each open token index to the index of its close token\nconst pair = (toks: Token[]) => {\n const pairs = new Map()\n const stack: number[] = []\n toks.forEach((tok, i) => {\n if (tok.t === 'open') stack.push(i)\n else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i)\n })\n return pairs\n}\n\n// build the alternatives between start and end. An open token that\n// is not closed is never inside a closed extglob, so bar and close\n// tokens are only literal at the top level.\nconst build = (\n toks: Token[],\n pairs: Map,\n start: number,\n end: number,\n top: boolean,\n): Item[][] => {\n let seq: Item[] = []\n const alts = [seq]\n for (let i = start; i < end; i++) {\n const tok = toks[i]!\n const close = pairs.get(i)\n if (tok.t === 'open' && close !== undefined) {\n const sub = build(toks, pairs, i + 1, close, false)\n seq.push({ t: 'ext', type: tok.type, alts: sub })\n i = close\n } else if (tok.t === 'bar' && !top) {\n alts.push((seq = []))\n } else if (tok.t === 'open') {\n seq.push(lit(tok.type), lit('('))\n } else if (tok.t === 'bar') {\n seq.push(lit('|'))\n } else if (tok.t === 'close') {\n seq.push(lit(')'))\n } else {\n seq.push(tok)\n }\n }\n return alts\n}\n\n// normalize each run of literal chars as one string, so that a char\n// and the combining marks after it compose (or decompose) together.\n// Syntax is already parsed, so a char that normalizes to a syntax\n// char (such as full-width `*` in NFKC) stays a literal.\nconst normalize = (items: Item[], form: Form): Item[] => {\n const out: Item[] = []\n let run = ''\n const flush = () => {\n for (const ch of run.normalize(form)) out.push(lit(ch))\n run = ''\n }\n for (const it of items) {\n if (it.t === 'lit') {\n run += it.ch\n continue\n }\n flush()\n out.push(\n it.t === 'ext' ?\n { ...it, alts: it.alts.map(a => normalize(a, form)) }\n : it,\n )\n }\n flush()\n return out\n}\n\n// the start node, and the number of node ids. Ids are dense, from 0\n// for the match node.\nconst compile = (\n items: Item[],\n nocase: boolean,\n): [start: Node, size: number] => {\n let id = 1\n const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out })\n const seq = (items: Item[], next: Node): Node =>\n items.reduceRight((next, it) => item(it, next), next)\n const item = (it: Item, next: Node): Node => {\n switch (it.t) {\n case 'lit':\n const re = nocase ? foldRe(it.ch) : undefined\n return { t: 'lit', id: id++, ch: it.ch, re, next }\n case 'any':\n case 'star':\n return { t: it.t, id: id++, next }\n case 'class':\n return { t: 'class', id: id++, re: it.re, next }\n }\n const alts = (next: Node) => it.alts.map(a => seq(a, next))\n switch (it.type) {\n case '@':\n return split(alts(next))\n case '?':\n return split([next, ...alts(next)])\n case '!':\n return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }\n }\n // * and +, loop back after each match\n const after = split([])\n const entry = split(alts(after))\n after.out.push(next, entry)\n return it.type === '*' ? after : entry\n }\n const start = seq(items, MATCH)\n return [start, id]\n}\n\n// one line per node, in the order that a walk from the start\n// reaches them. Edges point to node ids. The nodes of a negated\n// sub-pattern are indented under their negation.\nconst show = (start: Node): string => {\n const lines: string[] = []\n const seen = new Set()\n const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id))\n const walk = (n: Node, indent: string) => {\n if (n.t === 'match' || seen.has(n)) return\n seen.add(n)\n const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`)\n switch (n.t) {\n case 'split':\n line(`split -> ${n.out.map(ref).join(', ')}`)\n for (const o of n.out) walk(o, indent)\n return\n case 'neg':\n line(`!(${ref(n.sub)}) -> ${ref(n.next)}`)\n walk(n.sub, indent + ' ')\n return walk(n.next, indent)\n case 'lit':\n line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`)\n break\n case 'class':\n line(`${n.re} -> ${ref(n.next)}`)\n break\n default:\n line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`)\n }\n walk(n.next, indent)\n }\n walk(start, '')\n return [`start -> ${ref(start)}`, ...lines].join('\\n')\n}\n\n// A thread inside a !(...) negation. It holds the threads of the\n// negated sub-pattern, started where the negation started. The\n// negation matches the chars so far if the sub-pattern does not.\ntype Run = { t: 'run'; neg: NegNode; state: State }\n\n// The threads at one position in the string. Each node thread is\n// only kept once, and runs with the same state are only kept once,\n// so that identical threads merge. The match node is not in\n// `threads`, because it can not step. It sets `match` instead.\nclass State {\n // set by the Sim, to mark the nodes that this state has\n gen: number\n threads: Node[] = []\n match = false\n runs: Run[] = []\n // the sorted ids of the threads, with 0 for a match, once the\n // state is done\n ids: number[] = []\n\n constructor(gen: number) {\n this.gen = gen\n }\n\n // no threads, so nothing more can match\n get dead() {\n return !this.threads.length && !this.match && !this.runs.length\n }\n}\n\n// true if the two states hold the same threads\nconst sameState = (a: State, b: State): boolean => {\n if (a.ids.length !== b.ids.length) return false\n if (a.runs.length !== b.runs.length) return false\n if (a.ids.some((id, i) => id !== b.ids[i])) return false\n return a.runs.every(r =>\n b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)),\n )\n}\n\n/**\n * For each node id, the gen of the last state that has the node as\n * a thread, and of the last state that walked through it. A state is\n * built to the end before the states around it go on, and the nodes\n * of a negated sub-pattern are only in its states (other than the\n * match node, which is never marked). So one mark for each node is\n * enough to know if the state being built has it. The Sims of a\n * matcher never run at the same time, so they share one Marks.\n */\nexport type Marks = { has: Float64Array; seen: Float64Array; gen: number }\n\nconst marks = (size: number): Marks => ({\n has: new Float64Array(size),\n seen: new Float64Array(size),\n gen: 0,\n})\n\nclass Sim {\n // `.` and `..` only match literal dots, even with `dot:true`\n dots: boolean\n // the string starts with `.`, and `dot:true` is not set\n dotStart: boolean\n #marks: Marks\n\n constructor(dots: boolean, dotStart: boolean, marks: Marks) {\n this.dots = dots\n this.dotStart = dotStart\n this.#marks = marks\n }\n\n state() {\n return new State(++this.#marks.gen)\n }\n\n // sort the ids of a state, once it has all of its threads\n done(state: State) {\n state.ids = state.threads.map(n => n.id).sort((a, b) => a - b)\n if (state.match) state.ids.unshift(MATCH.id)\n return state\n }\n\n // true the first time that the state walks through the node, so\n // that loops in the graph stop\n #visit(state: State, node: Node) {\n const { seen } = this.#marks\n if (seen[node.id] === state.gen) return false\n seen[node.id] = state.gen\n return true\n }\n\n #addThread(state: State, node: Node) {\n const { has } = this.#marks\n if (has[node.id] === state.gen) return false\n has[node.id] = state.gen\n state.threads.push(node)\n return true\n }\n\n // wildcards only match a leading dot if `dot:true`. In a negated\n // sub-pattern, this does not apply, because the negation itself\n // can not match a leading dot.\n restricted(i: number, top: boolean) {\n return top && (this.dots || (this.dotStart && i === 0))\n }\n\n add(state: State, node: Node, i: number, top: boolean): void {\n switch (node.t) {\n case 'split':\n if (!this.#visit(state, node)) return\n for (const o of node.out) this.add(state, o, i, top)\n return\n case 'neg':\n if (!this.#visit(state, node)) return\n const sub = this.state()\n this.add(sub, node.sub, i, false)\n this.done(sub)\n return this.addRun(\n state,\n { t: 'run', neg: node, state: sub },\n i,\n top,\n )\n case 'star':\n // a * can not start a dotfile, even if it matches nothing\n if (this.restricted(i, top)) return\n if (this.#addThread(state, node))\n this.add(state, node.next, i, top)\n return\n case 'match':\n state.match = true\n return\n default:\n this.#addThread(state, node)\n }\n }\n\n addRun(state: State, run: Run, i: number, top: boolean) {\n for (const r of state.runs) {\n if (r.neg === run.neg && sameState(r.state, run.state)) return\n }\n state.runs.push(run)\n if (!run.state.match) {\n this.add(state, run.neg.next, i, top)\n }\n }\n\n // the threads after char `c`, at index `i`\n step(state: State, c: string, i: number, top: boolean): State {\n const next = this.state()\n for (const th of state.threads) {\n switch (th.t) {\n case 'lit':\n if (litMatch(th, c)) {\n this.add(next, th.next, i + 1, top)\n }\n break\n case 'any':\n if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top)\n break\n case 'class':\n if (!this.restricted(i, top) && th.re.test(c)) {\n this.add(next, th.next, i + 1, top)\n }\n break\n case 'star':\n if (!this.restricted(i, top)) this.add(next, th, i + 1, top)\n }\n }\n if (!this.restricted(i, top)) {\n for (const run of state.runs) {\n // a sub-pattern with no threads can not match again, so the\n // run stays the same\n if (run.state.dead) {\n this.addRun(next, run, i + 1, top)\n continue\n }\n const sub = this.step(run.state, c, i, false)\n this.addRun(\n next,\n { t: 'run', neg: run.neg, state: sub },\n i + 1,\n top,\n )\n }\n }\n return this.done(next)\n }\n}\n\n// A canonical key for the threads in a state. States with the same\n// key hold the same threads, so they match the same strings.\nconst stateKey = (state: State): string => {\n const ids = state.ids.join()\n if (!state.runs.length) return ids\n const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`)\n return `${ids}|${runs.sort().join('|')}`\n}\n\n// A cached state of the simulation, and the states that each char\n// leads to.\ntype DState = {\n state: State\n match: boolean\n // no threads, so nothing more can match\n dead: boolean\n // the next state for each ASCII char, by char code, and for the\n // other chars\n ascii?: (DState | undefined)[]\n next: Map\n}\n\n// The cache can hold about this many chars of state keys and\n// transitions. When it is full, it is cleared, so that a pattern\n// can not use an unbounded amount of memory.\nconst DFA_BUDGET = 1 << 18\n\n// A cache of the states that the simulation reaches, built as the\n// matcher is used. Each char of a string is then one Map lookup,\n// once the states that it leads to are known.\n//\n// The dot rules only restrict the first char of a dotfile (strings\n// that are only `.` or `..` do not use the cache). So a dotfile\n// starts at its own state, which takes its first step with the\n// restriction, and every other state takes steps without it.\nclass Dfa {\n #start: Node\n #states = new Map()\n #size = 0\n #plain?: DState\n #dotStart?: DState\n #sim: Sim\n #dotSim: Sim\n\n constructor(start: Node, marks: Marks) {\n this.#start = start\n this.#sim = new Sim(false, false, marks)\n this.#dotSim = new Sim(false, true, marks)\n }\n\n #make(state: State): DState {\n return {\n state,\n match: state.match,\n dead: state.dead,\n next: new Map(),\n }\n }\n\n #intern(state: State): DState {\n const key = stateKey(state)\n const found = this.#states.get(key)\n if (found) return found\n if (this.#size > DFA_BUDGET) this.#clear()\n const d = this.#make(state)\n this.#states.set(key, d)\n this.#size += key.length + 1\n return d\n }\n\n #clear() {\n this.#states.clear()\n this.#size = 0\n this.#plain = undefined\n this.#dotStart = undefined\n }\n\n start(dotStart: boolean): DState {\n if (dotStart) {\n if (this.#dotStart) return this.#dotStart\n const state = this.#dotSim.state()\n this.#dotSim.add(state, this.#start, 0, true)\n return (this.#dotStart = this.#make(this.#dotSim.done(state)))\n }\n if (this.#plain) return this.#plain\n const state = this.#sim.state()\n this.#sim.add(state, this.#start, 0, true)\n return (this.#plain = this.#intern(this.#sim.done(state)))\n }\n\n // the next state, after a miss in `d.ascii`\n next(d: DState, c: string): DState {\n const code = c.charCodeAt(0)\n const found = code < 128 ? undefined : d.next.get(c)\n if (found) return found\n // the dotfile start is not in the cache, so it is never shared\n const n =\n d === this.#dotStart ?\n this.#intern(this.#dotSim.step(d.state, c, 0, true))\n : this.#intern(this.#sim.step(d.state, c, 1, true))\n if (code < 128) {\n if (!d.ascii) {\n d.ascii = new Array(128)\n this.#size += 128\n }\n d.ascii[code] = n\n } else {\n d.next.set(c, n)\n }\n this.#size++\n return n\n }\n}\n\n/**\n * A node in a graph with no splits or negations. Such a graph is a\n * chain of nodes that each match one char, or a `*`.\n */\nexport type LinearNode = Exclude<\n Node,\n SplitNode | NegNode | { t: 'match' }\n>\n\n// the nodes in order, if the graph is a single chain\nconst linear = (start: Node): LinearNode[] | undefined => {\n const nodes: LinearNode[] = []\n for (let n = start; n.t !== 'match'; n = n.next) {\n if (n.t === 'split' || n.t === 'neg') return undefined\n nodes.push(n)\n }\n return nodes\n}\n\n// Match a chain of nodes. Each node other than `*` matches exactly\n// one char, so on a failure it is enough to go back to the last `*`\n// and let it match one more char. This takes at most\n// nodes.length * chars.length steps.\nconst testLinear = (\n nodes: LinearNode[],\n chars: ArrayLike,\n start: number,\n end: number,\n) => {\n let ni = 0\n let ci = start\n let starNi = -1\n let starCi = 0\n while (ci < end) {\n const n = nodes[ni]\n if (n?.t === 'star') {\n starNi = ni++\n starCi = ci\n continue\n }\n const c = chars[ci]!\n if (\n n &&\n (n.t === 'any' ||\n (n.t === 'lit' && litMatch(n, c)) ||\n (n.t === 'class' && n.re.test(c)))\n ) {\n ni++\n ci++\n continue\n }\n if (starNi === -1) return false\n ni = starNi + 1\n ci = ++starCi\n }\n while (nodes[ni]?.t === 'star') ni++\n return ni === nodes.length\n}\n\n// The least and most chars that the items can match. These are only\n// bounds: a negation can match a string of any length, so it counts\n// as 0 to Infinity.\nconst lengths = (items: Item[]): [min: number, max: number] => {\n let min = 0\n let max = 0\n for (const it of items) {\n const [lo, hi] = itemLengths(it)\n min += lo\n max += hi\n }\n return [min, max]\n}\n\nconst itemLengths = (it: Item): [min: number, max: number] => {\n if (it.t === 'star') return [0, Infinity]\n if (it.t !== 'ext') return [1, 1]\n if (it.type === '!') return [0, Infinity]\n const alts = it.alts.map(lengths)\n const min = Math.min(...alts.map(a => a[0]))\n const max = Math.max(...alts.map(a => a[1]))\n // a loop of alternatives that only match the empty string is empty\n const loop = max === 0 ? 0 : Infinity\n return (\n it.type === '@' ? [min, max]\n : it.type === '?' ? [0, max]\n : it.type === '*' ? [0, loop]\n : [min, loop]\n )\n}\n\n// true if the chars from `start` match the literals\nconst hasAffix = (\n lits: Lit[],\n chars: ArrayLike,\n start: number,\n) => {\n for (let j = 0; j < lits.length; j++) {\n if (!litMatch(lits[j]!, chars[start + j]!)) return false\n }\n return true\n}\n\n// a `/`, or half of a surrogate pair\nconst slashOrSurrogate = /[/\\ud800-\\udfff]/\nconst surrogate = /[\\ud800-\\udfff]/\n\n// a string can be indexed by code point, unless it has surrogate\n// pairs\nconst codePoints = (s: string): ArrayLike =>\n surrogate.test(s) ? [...s] : s\n\nconst noSlash = (s: string) => {\n if (s.includes('/')) {\n throw new Error('can only match a single path portion, got: ' + s)\n }\n}\n\nexport class Matcher {\n pattern: string\n options: MatcherOptions\n #start: Node\n // the number of node ids\n #size: number\n #marks?: Marks\n // the Sim for strings that are only `.` or `..`\n #dotsSim?: Sim\n // the string to compare, if the pattern has no magic. With\n // `nocase:true`, the RegExp that folds case is made when it is\n // first used.\n #literal?: string\n #literalFold = false\n #literalRe?: RegExp\n // the nodes between the prefix and suffix, if the graph is a\n // single chain\n #linear?: LinearNode[]\n // the linear nodes are only `*` and `?`, so the length bounds and\n // the prefix and suffix decide the match\n #wild = false\n // the least and most chars that a match can have\n #min = 0\n #max = Infinity\n // the literals that a match must start and end with. Each one\n // matches exactly one char, and they are distinct items in the\n // pattern, so a string that does not have them can not match.\n #prefix: Lit[] = []\n #suffix: Lit[] = []\n // the prefix and suffix as strings, if they do not fold case\n #prefixStr?: string\n #suffixStr?: string\n // there is a prefix or suffix to check\n #affix = false\n #dfa?: Dfa\n #form?: Form\n\n constructor(pattern: string, options: MatcherOptions = {}) {\n if (pattern.includes('/')) {\n throw new Error(\n 'can only match a single path portion, got pattern: ' + pattern,\n )\n }\n this.pattern = pattern\n this.options = options\n const { nocase = false, noext = false, normalize: n } = options\n this.#form = n === true ? 'NFC' : n || undefined\n // a pattern that is only an empty extglob is a literal string,\n // except for `!()`, which matches any non-empty string\n const literal = /^[?*+@]\\(\\)$/.test(pattern)\n const toks = tokenize(\n pattern,\n nocase,\n noext || literal,\n this.#form,\n options.rangeMark,\n )\n let [items] = build(toks, pair(toks), 0, toks.length, true)\n if (this.#form) items = normalize(items!, this.#form)\n const [start, size] = compile(items!, nocase)\n this.#start = start\n this.#size = size\n if (items!.every(it => it.t === 'lit')) {\n this.#literal = items!.map(it => it.ch).join('')\n this.#literalFold = nocase\n } else {\n const lit = (it: Item): Lit | undefined =>\n it.t !== 'lit' ? undefined\n : nocase ? { ch: it.ch, re: foldRe(it.ch) }\n : { ch: it.ch }\n for (const it of items!) {\n const l = lit(it)\n if (!l) break\n this.#prefix.push(l)\n }\n for (let j = items!.length - 1; j >= 0; j--) {\n const l = lit(items![j]!)\n if (!l) break\n this.#suffix.unshift(l)\n }\n this.#affix = !!(this.#prefix.length || this.#suffix.length)\n if (!nocase) {\n this.#prefixStr = this.#prefix.map(l => l.ch).join('')\n this.#suffixStr = this.#suffix.map(l => l.ch).join('')\n }\n this.#linear = linear(this.#start)?.slice(\n this.#prefix.length,\n -this.#suffix.length || undefined,\n )\n this.#wild = !!this.#linear?.every(\n n => n.t === 'star' || n.t === 'any',\n )\n const [min, max] = lengths(items!)\n this.#min = min\n this.#max = max\n }\n }\n\n test(s: string): boolean {\n // The `/` check uses the string as given, so with normalization it\n // is a separate step. Otherwise, one scan finds both a `/` and the\n // surrogate pairs that stop the string being indexed by code point.\n if (this.#form) {\n noSlash(s)\n return this.#test(s.normalize(this.#form))\n }\n if (slashOrSurrogate.test(s)) {\n noSlash(s)\n return this.#test(s, [...s])\n }\n return this.#test(s, s)\n }\n\n /**\n * The same as {@link Matcher#test}, but the string is not checked\n * for `/` chars, so the result for a string that has one is not\n * defined. Only use it for a string that is known to be one path\n * portion, such as a part of a path that was split on `/`. It can\n * be faster, because some patterns do not need to look at each char\n * of the string.\n */\n testUnchecked(s: string): boolean {\n return this.#test(this.#form ? s.normalize(this.#form) : s)\n }\n\n // Test a string that has no `/`. `chars` indexes it by code point.\n // If it is not given, it is only found if a step needs it.\n #test(s: string, chars?: ArrayLike): boolean {\n if (this.#literal !== undefined) {\n return this.#literalFold ?\n (this.#literalRe ??= newFoldRe(this.#literal)).test(s)\n : s === this.#literal\n }\n // the length check means that the prefix and suffix do not\n // overlap. Without the chars, the length in code points is from\n // half of the UTF-16 length (if each one is a surrogate pair) to\n // all of it, which is often enough to know.\n const min = this.#min\n const max = this.#max\n if (chars === undefined) {\n const most = s.length\n const least = (most + 1) >> 1\n if (most < min || least > max) return false\n if (least < min || most > max) chars = codePoints(s)\n }\n if (\n chars !== undefined &&\n (chars.length < min || chars.length > max)\n ) {\n return false\n }\n const prefix = this.#prefix.length\n if (this.#affix) {\n if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {\n if (\n !s.startsWith(this.#prefixStr) ||\n !s.endsWith(this.#suffixStr)\n ) {\n return false\n }\n } else {\n chars ??= codePoints(s)\n const end = chars.length - this.#suffix.length\n if (\n !hasAffix(this.#prefix, chars, 0) ||\n !hasAffix(this.#suffix, chars, end)\n ) {\n return false\n }\n }\n }\n const dotStart = !this.options.dot && s.startsWith('.')\n if (this.#linear) {\n // `.` and `..` only match literal dots, even with `dot:true`\n if (s === '.' || s === '..') return false\n // only a literal can match the leading dot. A `*` can not\n // start a dotfile, even if it matches nothing.\n if (dotStart && !prefix) return false\n if (this.#wild) return true\n chars ??= codePoints(s)\n const end = chars.length - this.#suffix.length\n return testLinear(this.#linear, chars, prefix, end)\n }\n chars ??= codePoints(s)\n if (s === '.' || s === '..') {\n this.#marks ??= marks(this.#size)\n const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks))\n const start = sim.state()\n sim.add(start, this.#start, 0, true)\n let state = sim.done(start)\n for (let i = 0; i < chars.length; i++) {\n state = sim.step(state, chars[i]!, i, true)\n }\n return state.match\n }\n this.#marks ??= marks(this.#size)\n const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks))\n let d = dfa.start(dotStart)\n // read char codes from the string, so that a one-char string is\n // only made for a cache miss\n const str = chars === s\n for (let i = 0; i < chars.length; i++) {\n if (d.dead) return false\n const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0)\n d = d.ascii?.[code] ?? dfa.next(d, chars[i]!)\n }\n return d.match\n }\n\n /** a readable listing of the state machine */\n toString(): string {\n return show(this.#start)\n }\n}\n"], + "mappings": "4MAGA,IAAMA,EAAQ,CAACC,EAAWC,IACxBD,IAAMC,EACJ,CAAE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IAAMoB,EAAM2E,EAAM,OAAS,KAAK6B,GAAQ,OACxC,OAAO9B,GAAW,KAAKyB,GAASxB,EAAOyC,EAAQpH,CAAG,CACpD,CAEA,GADA2E,IAAUiB,EAAWhH,CAAC,EAClBA,IAAM,KAAOA,IAAM,KAAM,CAC3B,KAAKiE,KAAWH,EAAM,KAAKmB,EAAK,EAChC,IAAMwD,EAAO,KAAKtB,KAAa,IAAInD,EAAI,GAAM,GAAO,KAAKC,EAAM,EACzD9C,EAAQsH,EAAI,MAAK,EACvBA,EAAI,IAAItH,EAAO,KAAK4D,GAAQ,EAAG,EAAI,EACnC,IAAIX,EAAQqE,EAAI,KAAKtH,CAAK,EAC1B,QAASF,EAAI,EAAGA,EAAI8E,EAAM,OAAQ9E,IAChCmD,EAAQqE,EAAI,KAAKrE,EAAO2B,EAAM9E,CAAC,EAAIA,EAAG,EAAI,EAE5C,OAAOmD,EAAM,KACf,CACA,KAAKH,KAAWH,EAAM,KAAKmB,EAAK,EAChC,IAAMyD,EAAO,KAAKV,KAAS,IAAIlD,EAAI,KAAKC,GAAQ,KAAKd,EAAM,EACvD0B,EAAI+C,EAAI,MAAMvE,CAAQ,EAGpBwE,EAAM5C,IAAU/F,EACtB,QAASiB,EAAI,EAAGA,EAAI8E,EAAM,OAAQ9E,IAAK,CACrC,GAAI0E,EAAE,KAAM,MAAO,GACnB,IAAMnF,EAAOmI,EAAM3I,EAAE,WAAWiB,CAAC,EAAI8E,EAAM9E,CAAC,EAAG,WAAW,CAAC,EAC3D0E,EAAIA,EAAE,QAAQnF,CAAI,GAAKkI,EAAI,KAAK/C,EAAGI,EAAM9E,CAAC,CAAE,CAC9C,CACA,OAAO0E,EAAE,KACX,CAGA,UAAQ,CACN,OAAO3C,GAAK,KAAK+B,EAAM,CACzB,GApNF,QAAA,QAAAmC", + "names": ["digit", "a", "b", "prefix", "d", "alts", "s", "fixed", "lo", "hi", "ra", "rb", "zeros", "nines", "out", "last", "nonneg", "width", "len", "numericRange", "loStr", "hiStr", "neg", "exports", "posixClasses", "braceEscape", "s", "noMatch", "parseClass", "glob", "position", "nocase", "form", "norm", "c", "n", "pos", "ranges", "negs", "i", "sawStart", "escaping", "negate", "endPos", "rangeStart", "WHILE", "cls", "unip", "neg", "sranges", "snegs", "comb", "exports", "numeric_range_js_1", "parse_class_js_1", "MATCH", "extTypes", "lit", "ch", "reEscape", "s", "newFoldRe", "foldCache", "foldRe", "re", "litMatch", "l", "c", "code", "ascii", "tokenize", "p", "nocase", "noext", "form", "mark", "toks", "i", "m", "start", "end", "r", "alts", "e", "consumed", "pair", "pairs", "stack", "tok", "build", "top", "seq", "close", "sub", "normalize", "items", "out", "run", "flush", "it", "a", "compile", "id", "split", "next", "item", "after", "entry", "show", "lines", "seen", "ref", "n", "walk", "indent", "line", "desc", "State", "gen", "sameState", "b", "o", "marks", "size", "Sim", "#marks", "dots", "dotStart", "state", "#visit", "node", "#addThread", "has", "th", "stateKey", "ids", "runs", "DFA_BUDGET", "Dfa", "#start", "#states", "#size", "#plain", "#dotStart", "#sim", "#dotSim", "#make", "#intern", "key", "found", "#clear", "d", "linear", "nodes", "testLinear", "chars", "ni", "ci", "starNi", "starCi", "lengths", "min", "max", "lo", "hi", "itemLengths", "loop", "hasAffix", "lits", "j", "slashOrSurrogate", "surrogate", "codePoints", "noSlash", "Matcher", "#dotsSim", "#literal", "#literalFold", "#literalRe", "#linear", "#wild", "#min", "#max", "#prefix", "#suffix", "#prefixStr", "#suffixStr", "#affix", "#dfa", "#form", "pattern", "options", "literal", "#test", "most", "least", "prefix", "sim", "dfa", "str"] +} diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.d.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e90c51724be67c053c23facbc3e3ab70f51c3368 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.d.ts @@ -0,0 +1,15 @@ +import type { Item } from './index.js'; +/** + * The strings that the bash brace expansion `{lo..hi}` makes, as + * the alternatives of an `@(...)` extglob. Each one is a sequence of + * digits and digit classes, so there are only a few of them, even for + * a large range. + * + * If either end has a leading zero, such as `{01..10}`, each number + * has leading zeros to make it as long as the longer end, counting a + * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`. + * + * Returns undefined if either end is not a safe integer. + */ +export declare const numericRange: (loStr: string, hiStr: string) => Item[][] | undefined; +//# sourceMappingURL=numeric-range.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.d.ts.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..2e3c35fc58538bed19bdf85b8a5ba977cd2007e7 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"numeric-range.d.ts","sourceRoot":"","sources":["../../src/numeric-range.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAiDtC;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,YAAY,GACvB,OAAO,MAAM,EACb,OAAO,MAAM,KACZ,IAAI,EAAE,EAAE,GAAG,SAcb,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.js b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.js new file mode 100644 index 0000000000000000000000000000000000000000..376d6f296ec6062b2870aab980b0b755d1d6d55d --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.js @@ -0,0 +1,76 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.numericRange = void 0; +// One digit, or a class of digits from a to b. +const digit = (a, b) => a === b ? + { t: 'lit', ch: String(a) } + : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) }; +const prefix = (d, alts) => alts.map(s => [digit(d, d), ...s]); +// The digit strings from a to b, which have the same length. +const fixed = (a, b) => { + if (!a) + return [[]]; + let lo = +a[0]; + let hi = +b[0]; + const ra = a.slice(1); + const rb = b.slice(1); + if (lo === hi) + return prefix(lo, fixed(ra, rb)); + const zeros = '0'.repeat(ra.length); + const nines = '9'.repeat(ra.length); + const out = []; + if (ra !== zeros) + out.push(...prefix(lo++, fixed(ra, nines))); + const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb)); + if (lo <= hi) { + out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))]); + } + out.push(...last); + return out; +}; +// The numbers from a to b, where 0 <= a <= b. If width is set, each +// one has leading zeros to make it that many digits. +const nonneg = (a, b, width) => { + if (width) { + return fixed(String(a).padStart(width, '0'), String(b).padStart(width, '0')); + } + const out = []; + for (let len = String(a).length; len <= String(b).length; len++) { + const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1)); + const hi = Math.min(b, 10 ** len - 1); + out.push(...fixed(String(lo), String(hi))); + } + return out; +}; +/** + * The strings that the bash brace expansion `{lo..hi}` makes, as + * the alternatives of an `@(...)` extglob. Each one is a sequence of + * digits and digit classes, so there are only a few of them, even for + * a large range. + * + * If either end has a leading zero, such as `{01..10}`, each number + * has leading zeros to make it as long as the longer end, counting a + * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`. + * + * Returns undefined if either end is not a safe integer. + */ +const numericRange = (loStr, hiStr) => { + let lo = Number(loStr); + let hi = Number(hiStr); + if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) + return; + if (lo > hi) + [lo, hi] = [hi, lo]; + const padded = /^-?0\d/.test(loStr) || /^-?0\d/.test(hiStr); + const width = padded ? Math.max(loStr.length, hiStr.length) : 0; + const out = []; + if (lo < 0) { + const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1); + out.push(...neg.map(s => [{ t: 'lit', ch: '-' }, ...s])); + } + if (hi >= 0) + out.push(...nonneg(Math.max(lo, 0), hi, width)); + return out; +}; +exports.numericRange = numericRange; +//# sourceMappingURL=numeric-range.js.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.js.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c8339c608f8dc9c45b264127936de0971b73be23 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/numeric-range.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numeric-range.js","sourceRoot":"","sources":["../../src/numeric-range.ts"],"names":[],"mappings":";;;AAEA,+CAA+C;AAC/C,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,CAAS,EAAQ,EAAE,CAC3C,CAAC,KAAK,CAAC,CAAC,CAAC;IACP,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE;IAC7B,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;AAEnD,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,IAAc,EAAE,EAAE,CAC3C,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAA;AAEpC,6DAA6D;AAC7D,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,CAAS,EAAY,EAAE;IAC/C,IAAI,CAAC,CAAC;QAAE,OAAO,CAAC,EAAE,CAAC,C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,CAAC;QAAE,OAAM;IAClE,IAAI,EAAE,GAAG,EAAE;QAAE,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;IAChC,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAC3D,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAC/D,MAAM,GAAG,GAAa,EAAE,CAAA;IACxB,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACX,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,IAAI,KAAK,GAAG,CAAC,CAAC,CAAA;QAC7D,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,GAAG,EAAU,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;IACD,IAAI,EAAE,IAAI,CAAC;QAAE,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC,CAAA;IAC5D,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAjBY,QAAA,YAAY,gBAiBxB","sourcesContent":["import type { Item } from './index.js'\n\n// One digit, or a class of digits from a to b.\nconst digit = (a: number, b: number): Item =>\n a === b ?\n { t: 'lit', ch: String(a) }\n : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) }\n\nconst prefix = (d: number, alts: Item[][]) =>\n alts.map(s => [digit(d, d), ...s])\n\n// The digit strings from a to b, which have the same length.\nconst fixed = (a: string, b: string): Item[][] => {\n if (!a) return [[]]\n let lo = +a[0]!\n let hi = +b[0]!\n const ra = a.slice(1)\n const rb = b.slice(1)\n if (lo === hi) return prefix(lo, fixed(ra, rb))\n const zeros = '0'.repeat(ra.length)\n const nines = '9'.repeat(ra.length)\n const out: Item[][] = []\n if (ra !== zeros) out.push(...prefix(lo++, fixed(ra, nines)))\n const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb))\n if (lo <= hi) {\n out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))])\n }\n out.push(...last)\n return out\n}\n\n// The numbers from a to b, where 0 <= a <= b. If width is set, each\n// one has leading zeros to make it that many digits.\nconst nonneg = (a: number, b: number, width: number): Item[][] => {\n if (width) {\n return fixed(\n String(a).padStart(width, '0'),\n String(b).padStart(width, '0'),\n )\n }\n const out: Item[][] = []\n for (let len = String(a).length; len <= String(b).length; len++) {\n const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1))\n const hi = Math.min(b, 10 ** len - 1)\n out.push(...fixed(String(lo), String(hi)))\n }\n return out\n}\n\n/**\n * The strings that the bash brace expansion `{lo..hi}` makes, as\n * the alternatives of an `@(...)` extglob. Each one is a sequence of\n * digits and digit classes, so there are only a few of them, even for\n * a large range.\n *\n * If either end has a leading zero, such as `{01..10}`, each number\n * has leading zeros to make it as long as the longer end, counting a\n * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`.\n *\n * Returns undefined if either end is not a safe integer.\n */\nexport const numericRange = (\n loStr: string,\n hiStr: string,\n): Item[][] | undefined => {\n let lo = Number(loStr)\n let hi = Number(hiStr)\n if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) return\n if (lo > hi) [lo, hi] = [hi, lo]\n const padded = /^-?0\\d/.test(loStr) || /^-?0\\d/.test(hiStr)\n const width = padded ? Math.max(loStr.length, hiStr.length) : 0\n const out: Item[][] = []\n if (lo < 0) {\n const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1)\n out.push(...neg.map(s => [{ t: 'lit', ch: '-' } as Item, ...s]))\n }\n if (hi >= 0) out.push(...nonneg(Math.max(lo, 0), hi, width))\n return out\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/package.json b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.d.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f0dbca07538fdb8bee4ed70b636da30c5f92b19 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.d.ts @@ -0,0 +1,4 @@ +export type ParseClassResult = [re: RegExp, consumed: number]; +export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'; +export declare const parseClass: (glob: string, position: number, nocase?: boolean, form?: Form) => ParseClassResult; +//# sourceMappingURL=parse-class.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.d.ts.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9edec7a94af01d9b1c8fcf1471b2548579159b83 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-class.d.ts","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAyBA,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AAE7D,MAAM,MAAM,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAA;AAWlD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,EAChB,SAAQ,OAAe,EACvB,OAAO,IAAI,KACV,gBAkHF,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.js b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.js similarity index 49% rename from mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.js rename to mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.js index 2b7b03712b874e29341dcb990f3b8b6163f145d4..c5de227c74435aff126c7fcac7392b28483e16cb 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.js +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.js @@ -3,37 +3,40 @@ // this works across all unicode locales Object.defineProperty(exports, "__esModule", { value: true }); exports.parseClass = void 0; -// { : [, /u flag required, negated] +// { : [, negated] const posixClasses = { - '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], - '[:alpha:]': ['\\p{L}\\p{Nl}', true], - '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], - '[:blank:]': ['\\p{Zs}\\t', true], - '[:cntrl:]': ['\\p{Cc}', true], - '[:digit:]': ['\\p{Nd}', true], - '[:graph:]': ['\\p{Z}\\p{C}', true, true], - '[:lower:]': ['\\p{Ll}', true], + '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'], + '[:alpha:]': ['\\p{L}\\p{Nl}'], + '[:ascii:]': ['\\x' + '00-\\x' + '7f'], + '[:blank:]': ['\\p{Zs}\\t'], + '[:cntrl:]': ['\\p{Cc}'], + '[:digit:]': ['\\p{Nd}'], + '[:graph:]': ['\\p{Z}\\p{C}', true], + '[:lower:]': ['\\p{Ll}'], '[:print:]': ['\\p{C}', true], - '[:punct:]': ['\\p{P}', true], - '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], - '[:upper:]': ['\\p{Lu}', true], - '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], - '[:xdigit:]': ['A-Fa-f0-9', false], + '[:punct:]': ['\\p{P}\\p{S}'], + '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'], + '[:upper:]': ['\\p{Lu}'], + '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'], + '[:xdigit:]': ['A-Fa-f0-9'], }; // only need to escape a few things inside of brace expressions // escapes: [ \ ] - const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); -// escape all regexp magic characters -const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); -// everything has already been escaped, we just have to join -const rangesToString = (ranges) => ranges.join(''); -// takes a glob string at a posix brace expression, and returns -// an equivalent regular expression source, and boolean indicating -// whether the /u flag needs to be applied, and the number of chars -// consumed to parse the character class. -// This also removes out of order ranges, and returns ($.) if the -// entire class just no good. -const parseClass = (glob, position) => { +const noMatch = /$./; +// Takes a glob string at a posix brace expression. Returns a RegExp +// that tests one character, and the number of glob chars consumed. +// If the class is not closed, consumed is 0, and the `[` must be +// treated as a literal character. +// Out of order ranges are removed. If nothing is left, the RegExp +// is `/$./`, and the rest of the glob is consumed, so that the +// whole glob cannot match. +const parseClass = (glob, position, nocase = false, form) => { + // normalize one class member, if it stays one code point + const norm = (c) => { + const n = form ? c.normalize(form) : c; + return [...n].length === 1 ? n : c; + }; const pos = position; /* c8 ignore start */ if (glob.charAt(pos) !== '[') { @@ -44,13 +47,12 @@ const parseClass = (glob, position) => { const negs = []; let i = pos + 1; let sawStart = false; - let uflag = false; let escaping = false; let negate = false; let endPos = pos; let rangeStart = ''; WHILE: while (i < glob.length) { - const c = glob.charAt(i); + const c = String.fromCodePoint(glob.codePointAt(i)); if ((c === '!' || c === '^') && i === pos + 1) { negate = true; i++; @@ -71,80 +73,70 @@ const parseClass = (glob, position) => { } if (c === '[' && !escaping) { // either a posix class, a collation equivalent, or just a [ - for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { + for (const [cls, [unip, neg]] of Object.entries(posixClasses)) { if (glob.startsWith(cls, i)) { // invalid, [a-[] is fine, but not [a-[:alpha]] if (rangeStart) { - return ['$.', false, glob.length - pos, true]; + return [noMatch, glob.length - pos]; } i += cls.length; if (neg) negs.push(unip); else ranges.push(unip); - uflag = uflag || u; continue WHILE; } } } // now it's just a normal character, effectively escaping = false; + const n = norm(c); if (rangeStart) { // throw this range away if it's not valid, but others // can still match. - if (c > rangeStart) { - ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); + if (n.codePointAt(0) > rangeStart.codePointAt(0)) { + ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n)); } - else if (c === rangeStart) { - ranges.push(braceEscape(c)); + else if (n === rangeStart) { + ranges.push(braceEscape(n)); } rangeStart = ''; - i++; + i += c.length; continue; } // now might be the start of a range. // can be either c-d or c-] or c] or c] at this point - if (glob.startsWith('-]', i + 1)) { - ranges.push(braceEscape(c + '-')); - i += 2; + if (glob.startsWith('-]', i + c.length)) { + ranges.push(braceEscape(n + '-')); + i += c.length + 1; continue; } - if (glob.startsWith('-', i + 1)) { - rangeStart = c; - i += 2; + if (glob.startsWith('-', i + c.length)) { + rangeStart = n; + i += c.length + 1; continue; } // not the start of a range, just a single character - ranges.push(braceEscape(c)); - i++; + ranges.push(braceEscape(n)); + i += c.length; } if (endPos < i) { // didn't see the end of the class, not a valid class, // but might still be valid as a literal match. - return ['', false, 0, false]; + return [noMatch, 0]; } // if we got no ranges and no negates, then we have a range that // cannot possibly match anything, and that poisons the whole glob if (!ranges.length && !negs.length) { - return ['$.', false, glob.length - pos, true]; - } - // if we got one positive range, and it's a single character, then that's - // not actually a magic pattern, it's just that one literal character. - // we should not treat that as "magic", we should just return the literal - // character. [_] is a perfectly valid way to escape glob magic chars. - if (negs.length === 0 && - ranges.length === 1 && - /^\\?.$/.test(ranges[0]) && - !negate) { - const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; - return [regexpEscape(r), false, endPos - pos, false]; + return [noMatch, glob.length - pos]; } - const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; - const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; - const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' - : ranges.length ? sranges - : snegs; - return [comb, uflag, endPos - pos, true]; + const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'; + const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'; + const comb = '^' + + (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' + : ranges.length ? sranges + : snegs); + return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]; }; exports.parseClass = parseClass; -//# sourceMappingURL=brace-expressions.js.map \ No newline at end of file +//# sourceMappingURL=parse-class.js.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.js.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.js.map new file mode 100644 index 0000000000000000000000000000000000000000..417366c10b9a9eba94a5255f647b43da2a359494 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/commonjs/parse-class.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-class.js","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,wCAAwC;;;AAExC,4CAA4C;AAC5C,MAAM,YAAY,GAA8C;IAC9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C,EAAE,CAAC,GAAG,GAAG,CAAA;IAC7D,MAAM,IAAI,GACR,GAAG;QACH,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG;YACjE,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;gBACzB,CAAC,CAAC,KAAK,CAAC,CAAA;IAEV,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,CAAA;AAC9D,CAAC,CAAA;AAvHY,QAAA,UAAU,cAuHtB","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n '[:blank:]': ['\\\\p{Zs}\\\\t'],\n '[:cntrl:]': ['\\\\p{Cc}'],\n '[:digit:]': ['\\\\p{Nd}'],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n '[:lower:]': ['\\\\p{Ll}'],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n '[:upper:]': ['\\\\p{Lu}'],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n glob: string,\n position: number,\n nocase: boolean = false,\n form?: Form,\n): ParseClassResult => {\n // normalize one class member, if it stays one code point\n const norm = (c: string) => {\n const n = form ? c.normalize(form) : c\n return [...n].length === 1 ? n : c\n }\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = String.fromCodePoint(glob.codePointAt(i)!)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return [noMatch, glob.length - pos]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n const n = norm(c)\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n } else if (n === rangeStart) {\n ranges.push(braceEscape(n))\n }\n rangeStart = ''\n i += c.length\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + c.length)) {\n ranges.push(braceEscape(n + '-'))\n i += c.length + 1\n continue\n }\n if (glob.startsWith('-', i + c.length)) {\n rangeStart = n\n i += c.length + 1\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(n))\n i += c.length\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return [noMatch, 0]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return [noMatch, glob.length - pos]\n }\n\n const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n const comb =\n '^' +\n (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs)\n\n return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.d.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8353cdbc8a5a11e120d8df5476a51b45bdc98cc --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.d.ts @@ -0,0 +1,123 @@ +import { type Form } from './parse-class.js'; +export type { Form }; +export type MatcherOptions = { + /** perform a case-insensitive match */ + nocase?: boolean; + /** do not treat strings starting with `.` specially */ + dot?: boolean; + /** do not match extglobs (treat them as normal strings) */ + noext?: boolean; + /** + * normalize unicode in the pattern and the tested strings, with + * this form. `true` means `'NFC'`. + */ + normalize?: boolean | Form; + /** + * A char that marks a numeric range in the pattern, as + * `..`, where `lo` and `hi` are integers. It + * matches the strings that the bash brace expansion `{..}` + * makes, such as `{1..100}` or `{001..100}`, without making each + * one. A mark is never escaped by a `\` before it. Inside a `[...]` + * class, a mark is a char of the class. + */ + rangeMark?: string; +}; +export type Item = { + t: 'lit'; + ch: string; +} | { + t: 'any' | 'star'; +} | { + t: 'class'; + re: RegExp; +} | { + t: 'ext'; + type: string; + alts: Item[][]; +}; +export type Token = Item | { + t: 'open'; + type: string; +} | { + t: 'bar'; +} | { + t: 'close'; +}; +export type NegNode = { + t: 'neg'; + id: number; + sub: Node; + next: Node; +}; +export type SplitNode = { + t: 'split'; + id: number; + out: Node[]; +}; +export type Node = ({ + t: 'lit'; + id: number; + next: Node; +} & Lit) | { + t: 'any' | 'star'; + id: number; + next: Node; +} | { + t: 'class'; + id: number; + re: RegExp; + next: Node; +} | SplitNode | NegNode | { + t: 'match'; + id: number; +}; +/** + * A literal char. With `nocase:true`, `re` folds case, and `ascii` + * holds its results for ASCII chars, by char code: 1 for a match, + * and 2 for not. + */ +export type Lit = { + ch: string; + re?: RegExp; + ascii?: Uint8Array; +}; +/** + * For each node id, the gen of the last state that has the node as + * a thread, and of the last state that walked through it. A state is + * built to the end before the states around it go on, and the nodes + * of a negated sub-pattern are only in its states (other than the + * match node, which is never marked). So one mark for each node is + * enough to know if the state being built has it. The Sims of a + * matcher never run at the same time, so they share one Marks. + */ +export type Marks = { + has: Float64Array; + seen: Float64Array; + gen: number; +}; +/** + * A node in a graph with no splits or negations. Such a graph is a + * chain of nodes that each match one char, or a `*`. + */ +export type LinearNode = Exclude; +export declare class Matcher { + #private; + pattern: string; + options: MatcherOptions; + constructor(pattern: string, options?: MatcherOptions); + test(s: string): boolean; + /** + * The same as {@link Matcher#test}, but the string is not checked + * for `/` chars, so the result for a string that has one is not + * defined. Only use it for a string that is known to be one path + * portion, such as a part of a path that was split on `/`. It can + * be faster, because some patterns do not need to look at each char + * of the string. + */ + testUnchecked(s: string): boolean; + /** a readable listing of the state machine */ + toString(): string; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.d.ts.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..67993640d5ac0f5c3ae4b6910cab2dc96e04affc --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,IAAI,EAAc,MAAM,kBAAkB,CAAA;AAExD,YAAY,EAAE,IAAI,EAAE,CAAA;AAEpB,MAAM,MAAM,cAAc,GAAG;IAC3B,uCAAuC;IACvC,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,uDAAuD;IACvD,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,2DAA2D;IAC3D,KAAK,CAAC,EAAE,OAAO,CAAA;IACf;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;IAC1B;;;;;;;OAOG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAA;AAGD,MAAM,MAAM,IAAI,GACZ;IAAE,CAAC,EAAE,KAAK,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GACxB;IAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAAA;CAAE,GACrB;IAAE,CAAC,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAC1B;IAAE,CAAC,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAA;CAAE,CAAA;AAI9C,MAAM,MAAM,KAAK,GACf,IAAI,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;I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M,UAAU,GAAG,OAAO,CAC9B,IAAI,EACJ,SAAS,GAAG,OAAO,GAAG;IAAE,CAAC,EAAE,OAAO,CAAA;CAAE,CACrC,CAAA;AA8GD,qBAAa,OAAO;;IAClB,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,cAAc,CAAA;gBAmCX,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;IA6DzD,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;IAexB;;;;;;;OAOG;IACH,aAAa,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;IAwFjC,8CAA8C;IAC9C,QAAQ,IAAI,MAAM;CAGnB"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.js b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2def91caa8aacbd499c12499c44d4d1dd73bc656 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.js @@ -0,0 +1,774 @@ +import { numericRange } from './numeric-range.js'; +import { parseClass } from './parse-class.js'; +// the end of the pattern, or of a negated sub-pattern +const MATCH = { t: 'match', id: 0 }; +const extTypes = '!?+*@'; +const lit = (ch) => ({ t: 'lit', ch }); +const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&'); +// a RegExp that only matches `s`, with unicode case folding +const newFoldRe = (s) => new RegExp(`^${reEscape(s)}$`, 'iu'); +// foldRe for one literal char. The same chars are in most patterns, +// so keep them. A RegExp without the `g` or `y` flag has no state to +// share. +const foldCache = new Map(); +const foldRe = (ch) => { + let re = foldCache.get(ch); + if (!re) { + re = newFoldRe(ch); + if (foldCache.size >= 1000) + foldCache.clear(); + foldCache.set(ch, re); + } + return re; +}; +const litMatch = (l, c) => { + if (c === l.ch) + return true; + if (!l.re) + return false; + const code = c.charCodeAt(0); + if (code >= 128) + return l.re.test(c); + const ascii = (l.ascii ??= new Uint8Array(128)); + ascii[code] ||= l.re.test(c) ? 1 : 2; + return ascii[code] === 1; +}; +const tokenize = (p, nocase, noext, form, mark) => { + const toks = []; + for (let i = 0; i < p.length;) { + const c = String.fromCodePoint(p.codePointAt(i)); + if (mark) { + // a \ before a range would only escape its first char + const m = c === '\\' && p.startsWith(mark, i + 1) ? 1 : 0; + if (m || c === mark) { + const start = i + m + mark.length; + const end = p.indexOf(mark, start); + const r = /^(-?\d+)\.\.(-?\d+)$/.exec(p.slice(start, end)); + const alts = end !== -1 && r && numericRange(r[1], r[2]); + if (alts) { + toks.push({ t: 'ext', type: '@', alts }); + i = end + mark.length; + continue; + } + } + } + if (c === '\\') { + // a trailing \ is a literal \ + const e = p.codePointAt(i + 1); + const ch = e === undefined ? c : String.fromCodePoint(e); + toks.push(lit(ch)); + i += 1 + ch.length; + continue; + } + if (c === '[') { + const [re, consumed] = parseClass(p, i, nocase, form); + if (consumed) { + toks.push({ t: 'class', re }); + i += consumed; + continue; + } + } + if (!noext && extTypes.includes(c) && p[i + 1] === '(') { + toks.push({ t: 'open', type: c }); + i += 2; + continue; + } + toks.push(!noext && c === '|' ? { t: 'bar' } + : !noext && c === ')' ? { t: 'close' } + : c === '*' ? { t: 'star' } + : c === '?' ? { t: 'any' } + : lit(c)); + i += c.length; + } + return toks; +}; +// map each open token index to the index of its close token +const pair = (toks) => { + const pairs = new Map(); + const stack = []; + toks.forEach((tok, i) => { + if (tok.t === 'open') + stack.push(i); + else if (tok.t === 'close' && stack.length) + pairs.set(stack.pop(), i); + }); + return pairs; +}; +// build the alternatives between start and end. An open token that +// is not closed is never inside a closed extglob, so bar and close +// tokens are only literal at the top level. +const build = (toks, pairs, start, end, top) => { + let seq = []; + const alts = [seq]; + for (let i = start; i < end; i++) { + const tok = toks[i]; + const close = pairs.get(i); + if (tok.t === 'open' && close !== undefined) { + const sub = build(toks, pairs, i + 1, close, false); + seq.push({ t: 'ext', type: tok.type, alts: sub }); + i = close; + } + else if (tok.t === 'bar' && !top) { + alts.push((seq = [])); + } + else if (tok.t === 'open') { + seq.push(lit(tok.type), lit('(')); + } + else if (tok.t === 'bar') { + seq.push(lit('|')); + } + else if (tok.t === 'close') { + seq.push(lit(')')); + } + else { + seq.push(tok); + } + } + return alts; +}; +// normalize each run of literal chars as one string, so that a char +// and the combining marks after it compose (or decompose) together. +// Syntax is already parsed, so a char that normalizes to a syntax +// char (such as full-width `*` in NFKC) stays a literal. +const normalize = (items, form) => { + const out = []; + let run = ''; + const flush = () => { + for (const ch of run.normalize(form)) + out.push(lit(ch)); + run = ''; + }; + for (const it of items) { + if (it.t === 'lit') { + run += it.ch; + continue; + } + flush(); + out.push(it.t === 'ext' ? + { ...it, alts: it.alts.map(a => normalize(a, form)) } + : it); + } + flush(); + return out; +}; +// the start node, and the number of node ids. Ids are dense, from 0 +// for the match node. +const compile = (items, nocase) => { + let id = 1; + const split = (out) => ({ t: 'split', id: id++, out }); + const seq = (items, next) => items.reduceRight((next, it) => item(it, next), next); + const item = (it, next) => { + switch (it.t) { + case 'lit': + const re = nocase ? foldRe(it.ch) : undefined; + return { t: 'lit', id: id++, ch: it.ch, re, next }; + case 'any': + case 'star': + return { t: it.t, id: id++, next }; + case 'class': + return { t: 'class', id: id++, re: it.re, next }; + } + const alts = (next) => it.alts.map(a => seq(a, next)); + switch (it.type) { + case '@': + return split(alts(next)); + case '?': + return split([next, ...alts(next)]); + case '!': + return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }; + } + // * and +, loop back after each match + const after = split([]); + const entry = split(alts(after)); + after.out.push(next, entry); + return it.type === '*' ? after : entry; + }; + const start = seq(items, MATCH); + return [start, id]; +}; +// one line per node, in the order that a walk from the start +// reaches them. Edges point to node ids. The nodes of a negated +// sub-pattern are indented under their negation. +const show = (start) => { + const lines = []; + const seen = new Set(); + const ref = (n) => (n.t === 'match' ? 'match' : String(n.id)); + const walk = (n, indent) => { + if (n.t === 'match' || seen.has(n)) + return; + seen.add(n); + const line = (desc) => lines.push(`${indent}${n.id}: ${desc}`); + switch (n.t) { + case 'split': + line(`split -> ${n.out.map(ref).join(', ')}`); + for (const o of n.out) + walk(o, indent); + return; + case 'neg': + line(`!(${ref(n.sub)}) -> ${ref(n.next)}`); + walk(n.sub, indent + ' '); + return walk(n.next, indent); + case 'lit': + line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`); + break; + case 'class': + line(`${n.re} -> ${ref(n.next)}`); + break; + default: + line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`); + } + walk(n.next, indent); + }; + walk(start, ''); + return [`start -> ${ref(start)}`, ...lines].join('\n'); +}; +// The threads at one position in the string. Each node thread is +// only kept once, and runs with the same state are only kept once, +// so that identical threads merge. The match node is not in +// `threads`, because it can not step. It sets `match` instead. +class State { + // set by the Sim, to mark the nodes that this state has + gen; + threads = []; + match = false; + runs = []; + // the sorted ids of the threads, with 0 for a match, once the + // state is done + ids = []; + constructor(gen) { + this.gen = gen; + } + // no threads, so nothing more can match + get dead() { + return !this.threads.length && !this.match && !this.runs.length; + } +} +// true if the two states hold the same threads +const sameState = (a, b) => { + if (a.ids.length !== b.ids.length) + return false; + if (a.runs.length !== b.runs.length) + return false; + if (a.ids.some((id, i) => id !== b.ids[i])) + return false; + return a.runs.every(r => b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state))); +}; +const marks = (size) => ({ + has: new Float64Array(size), + seen: new Float64Array(size), + gen: 0, +}); +class Sim { + // `.` and `..` only match literal dots, even with `dot:true` + dots; + // the string starts with `.`, and `dot:true` is not set + dotStart; + #marks; + constructor(dots, dotStart, marks) { + this.dots = dots; + this.dotStart = dotStart; + this.#marks = marks; + } + state() { + return new State(++this.#marks.gen); + } + // sort the ids of a state, once it has all of its threads + done(state) { + state.ids = state.threads.map(n => n.id).sort((a, b) => a - b); + if (state.match) + state.ids.unshift(MATCH.id); + return state; + } + // true the first time that the state walks through the node, so + // that loops in the graph stop + #visit(state, node) { + const { seen } = this.#marks; + if (seen[node.id] === state.gen) + return false; + seen[node.id] = state.gen; + return true; + } + #addThread(state, node) { + const { has } = this.#marks; + if (has[node.id] === state.gen) + return false; + has[node.id] = state.gen; + state.threads.push(node); + return true; + } + // wildcards only match a leading dot if `dot:true`. In a negated + // sub-pattern, this does not apply, because the negation itself + // can not match a leading dot. + restricted(i, top) { + return top && (this.dots || (this.dotStart && i === 0)); + } + add(state, node, i, top) { + switch (node.t) { + case 'split': + if (!this.#visit(state, node)) + return; + for (const o of node.out) + this.add(state, o, i, top); + return; + case 'neg': + if (!this.#visit(state, node)) + return; + const sub = this.state(); + this.add(sub, node.sub, i, false); + this.done(sub); + return this.addRun(state, { t: 'run', neg: node, state: sub }, i, top); + case 'star': + // a * can not start a dotfile, even if it matches nothing + if (this.restricted(i, top)) + return; + if (this.#addThread(state, node)) + this.add(state, node.next, i, top); + return; + case 'match': + state.match = true; + return; + default: + this.#addThread(state, node); + } + } + addRun(state, run, i, top) { + for (const r of state.runs) { + if (r.neg === run.neg && sameState(r.state, run.state)) + return; + } + state.runs.push(run); + if (!run.state.match) { + this.add(state, run.neg.next, i, top); + } + } + // the threads after char `c`, at index `i` + step(state, c, i, top) { + const next = this.state(); + for (const th of state.threads) { + switch (th.t) { + case 'lit': + if (litMatch(th, c)) { + this.add(next, th.next, i + 1, top); + } + break; + case 'any': + if (!this.restricted(i, top)) + this.add(next, th.next, i + 1, top); + break; + case 'class': + if (!this.restricted(i, top) && th.re.test(c)) { + this.add(next, th.next, i + 1, top); + } + break; + case 'star': + if (!this.restricted(i, top)) + this.add(next, th, i + 1, top); + } + } + if (!this.restricted(i, top)) { + for (const run of state.runs) { + // a sub-pattern with no threads can not match again, so the + // run stays the same + if (run.state.dead) { + this.addRun(next, run, i + 1, top); + continue; + } + const sub = this.step(run.state, c, i, false); + this.addRun(next, { t: 'run', neg: run.neg, state: sub }, i + 1, top); + } + } + return this.done(next); + } +} +// A canonical key for the threads in a state. States with the same +// key hold the same threads, so they match the same strings. +const stateKey = (state) => { + const ids = state.ids.join(); + if (!state.runs.length) + return ids; + const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`); + return `${ids}|${runs.sort().join('|')}`; +}; +// The cache can hold about this many chars of state keys and +// transitions. When it is full, it is cleared, so that a pattern +// can not use an unbounded amount of memory. +const DFA_BUDGET = 1 << 18; +// A cache of the states that the simulation reaches, built as the +// matcher is used. Each char of a string is then one Map lookup, +// once the states that it leads to are known. +// +// The dot rules only restrict the first char of a dotfile (strings +// that are only `.` or `..` do not use the cache). So a dotfile +// starts at its own state, which takes its first step with the +// restriction, and every other state takes steps without it. +class Dfa { + #start; + #states = new Map(); + #size = 0; + #plain; + #dotStart; + #sim; + #dotSim; + constructor(start, marks) { + this.#start = start; + this.#sim = new Sim(false, false, marks); + this.#dotSim = new Sim(false, true, marks); + } + #make(state) { + return { + state, + match: state.match, + dead: state.dead, + next: new Map(), + }; + } + #intern(state) { + const key = stateKey(state); + const found = this.#states.get(key); + if (found) + return found; + if (this.#size > DFA_BUDGET) + this.#clear(); + const d = this.#make(state); + this.#states.set(key, d); + this.#size += key.length + 1; + return d; + } + #clear() { + this.#states.clear(); + this.#size = 0; + this.#plain = undefined; + this.#dotStart = undefined; + } + start(dotStart) { + if (dotStart) { + if (this.#dotStart) + return this.#dotStart; + const state = this.#dotSim.state(); + this.#dotSim.add(state, this.#start, 0, true); + return (this.#dotStart = this.#make(this.#dotSim.done(state))); + } + if (this.#plain) + return this.#plain; + const state = this.#sim.state(); + this.#sim.add(state, this.#start, 0, true); + return (this.#plain = this.#intern(this.#sim.done(state))); + } + // the next state, after a miss in `d.ascii` + next(d, c) { + const code = c.charCodeAt(0); + const found = code < 128 ? undefined : d.next.get(c); + if (found) + return found; + // the dotfile start is not in the cache, so it is never shared + const n = d === this.#dotStart ? + this.#intern(this.#dotSim.step(d.state, c, 0, true)) + : this.#intern(this.#sim.step(d.state, c, 1, true)); + if (code < 128) { + if (!d.ascii) { + d.ascii = new Array(128); + this.#size += 128; + } + d.ascii[code] = n; + } + else { + d.next.set(c, n); + } + this.#size++; + return n; + } +} +// the nodes in order, if the graph is a single chain +const linear = (start) => { + const nodes = []; + for (let n = start; n.t !== 'match'; n = n.next) { + if (n.t === 'split' || n.t === 'neg') + return undefined; + nodes.push(n); + } + return nodes; +}; +// Match a chain of nodes. Each node other than `*` matches exactly +// one char, so on a failure it is enough to go back to the last `*` +// and let it match one more char. This takes at most +// nodes.length * chars.length steps. +const testLinear = (nodes, chars, start, end) => { + let ni = 0; + let ci = start; + let starNi = -1; + let starCi = 0; + while (ci < end) { + const n = nodes[ni]; + if (n?.t === 'star') { + starNi = ni++; + starCi = ci; + continue; + } + const c = chars[ci]; + if (n && + (n.t === 'any' || + (n.t === 'lit' && litMatch(n, c)) || + (n.t === 'class' && n.re.test(c)))) { + ni++; + ci++; + continue; + } + if (starNi === -1) + return false; + ni = starNi + 1; + ci = ++starCi; + } + while (nodes[ni]?.t === 'star') + ni++; + return ni === nodes.length; +}; +// The least and most chars that the items can match. These are only +// bounds: a negation can match a string of any length, so it counts +// as 0 to Infinity. +const lengths = (items) => { + let min = 0; + let max = 0; + for (const it of items) { + const [lo, hi] = itemLengths(it); + min += lo; + max += hi; + } + return [min, max]; +}; +const itemLengths = (it) => { + if (it.t === 'star') + return [0, Infinity]; + if (it.t !== 'ext') + return [1, 1]; + if (it.type === '!') + return [0, Infinity]; + const alts = it.alts.map(lengths); + const min = Math.min(...alts.map(a => a[0])); + const max = Math.max(...alts.map(a => a[1])); + // a loop of alternatives that only match the empty string is empty + const loop = max === 0 ? 0 : Infinity; + return (it.type === '@' ? [min, max] + : it.type === '?' ? [0, max] + : it.type === '*' ? [0, loop] + : [min, loop]); +}; +// true if the chars from `start` match the literals +const hasAffix = (lits, chars, start) => { + for (let j = 0; j < lits.length; j++) { + if (!litMatch(lits[j], chars[start + j])) + return false; + } + return true; +}; +// a `/`, or half of a surrogate pair +const slashOrSurrogate = /[/\ud800-\udfff]/; +const surrogate = /[\ud800-\udfff]/; +// a string can be indexed by code point, unless it has surrogate +// pairs +const codePoints = (s) => surrogate.test(s) ? [...s] : s; +const noSlash = (s) => { + if (s.includes('/')) { + throw new Error('can only match a single path portion, got: ' + s); + } +}; +export class Matcher { + pattern; + options; + #start; + // the number of node ids + #size; + #marks; + // the Sim for strings that are only `.` or `..` + #dotsSim; + // the string to compare, if the pattern has no magic. With + // `nocase:true`, the RegExp that folds case is made when it is + // first used. + #literal; + #literalFold = false; + #literalRe; + // the nodes between the prefix and suffix, if the graph is a + // single chain + #linear; + // the linear nodes are only `*` and `?`, so the length bounds and + // the prefix and suffix decide the match + #wild = false; + // the least and most chars that a match can have + #min = 0; + #max = Infinity; + // the literals that a match must start and end with. Each one + // matches exactly one char, and they are distinct items in the + // pattern, so a string that does not have them can not match. + #prefix = []; + #suffix = []; + // the prefix and suffix as strings, if they do not fold case + #prefixStr; + #suffixStr; + // there is a prefix or suffix to check + #affix = false; + #dfa; + #form; + constructor(pattern, options = {}) { + if (pattern.includes('/')) { + throw new Error('can only match a single path portion, got pattern: ' + pattern); + } + this.pattern = pattern; + this.options = options; + const { nocase = false, noext = false, normalize: n } = options; + this.#form = n === true ? 'NFC' : n || undefined; + // a pattern that is only an empty extglob is a literal string, + // except for `!()`, which matches any non-empty string + const literal = /^[?*+@]\(\)$/.test(pattern); + const toks = tokenize(pattern, nocase, noext || literal, this.#form, options.rangeMark); + let [items] = build(toks, pair(toks), 0, toks.length, true); + if (this.#form) + items = normalize(items, this.#form); + const [start, size] = compile(items, nocase); + this.#start = start; + this.#size = size; + if (items.every(it => it.t === 'lit')) { + this.#literal = items.map(it => it.ch).join(''); + this.#literalFold = nocase; + } + else { + const lit = (it) => it.t !== 'lit' ? undefined + : nocase ? { ch: it.ch, re: foldRe(it.ch) } + : { ch: it.ch }; + for (const it of items) { + const l = lit(it); + if (!l) + break; + this.#prefix.push(l); + } + for (let j = items.length - 1; j >= 0; j--) { + const l = lit(items[j]); + if (!l) + break; + this.#suffix.unshift(l); + } + this.#affix = !!(this.#prefix.length || this.#suffix.length); + if (!nocase) { + this.#prefixStr = this.#prefix.map(l => l.ch).join(''); + this.#suffixStr = this.#suffix.map(l => l.ch).join(''); + } + this.#linear = linear(this.#start)?.slice(this.#prefix.length, -this.#suffix.length || undefined); + this.#wild = !!this.#linear?.every(n => n.t === 'star' || n.t === 'any'); + const [min, max] = lengths(items); + this.#min = min; + this.#max = max; + } + } + test(s) { + // The `/` check uses the string as given, so with normalization it + // is a separate step. Otherwise, one scan finds both a `/` and the + // surrogate pairs that stop the string being indexed by code point. + if (this.#form) { + noSlash(s); + return this.#test(s.normalize(this.#form)); + } + if (slashOrSurrogate.test(s)) { + noSlash(s); + return this.#test(s, [...s]); + } + return this.#test(s, s); + } + /** + * The same as {@link Matcher#test}, but the string is not checked + * for `/` chars, so the result for a string that has one is not + * defined. Only use it for a string that is known to be one path + * portion, such as a part of a path that was split on `/`. It can + * be faster, because some patterns do not need to look at each char + * of the string. + */ + testUnchecked(s) { + return this.#test(this.#form ? s.normalize(this.#form) : s); + } + // Test a string that has no `/`. `chars` indexes it by code point. + // If it is not given, it is only found if a step needs it. + #test(s, chars) { + if (this.#literal !== undefined) { + return this.#literalFold ? + (this.#literalRe ??= newFoldRe(this.#literal)).test(s) + : s === this.#literal; + } + // the length check means that the prefix and suffix do not + // overlap. Without the chars, the length in code points is from + // half of the UTF-16 length (if each one is a surrogate pair) to + // all of it, which is often enough to know. + const min = this.#min; + const max = this.#max; + if (chars === undefined) { + const most = s.length; + const least = (most + 1) >> 1; + if (most < min || least > max) + return false; + if (least < min || most > max) + chars = codePoints(s); + } + if (chars !== undefined && + (chars.length < min || chars.length > max)) { + return false; + } + const prefix = this.#prefix.length; + if (this.#affix) { + if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) { + if (!s.startsWith(this.#prefixStr) || + !s.endsWith(this.#suffixStr)) { + return false; + } + } + else { + chars ??= codePoints(s); + const end = chars.length - this.#suffix.length; + if (!hasAffix(this.#prefix, chars, 0) || + !hasAffix(this.#suffix, chars, end)) { + return false; + } + } + } + const dotStart = !this.options.dot && s.startsWith('.'); + if (this.#linear) { + // `.` and `..` only match literal dots, even with `dot:true` + if (s === '.' || s === '..') + return false; + // only a literal can match the leading dot. A `*` can not + // start a dotfile, even if it matches nothing. + if (dotStart && !prefix) + return false; + if (this.#wild) + return true; + chars ??= codePoints(s); + const end = chars.length - this.#suffix.length; + return testLinear(this.#linear, chars, prefix, end); + } + chars ??= codePoints(s); + if (s === '.' || s === '..') { + this.#marks ??= marks(this.#size); + const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks)); + const start = sim.state(); + sim.add(start, this.#start, 0, true); + let state = sim.done(start); + for (let i = 0; i < chars.length; i++) { + state = sim.step(state, chars[i], i, true); + } + return state.match; + } + this.#marks ??= marks(this.#size); + const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks)); + let d = dfa.start(dotStart); + // read char codes from the string, so that a one-char string is + // only made for a cache miss + const str = chars === s; + for (let i = 0; i < chars.length; i++) { + if (d.dead) + return false; + const code = str ? s.charCodeAt(i) : chars[i].charCodeAt(0); + d = d.ascii?.[code] ?? dfa.next(d, chars[i]); + } + return d.match; + } + /** a readable listing of the state machine */ + toString() { + return show(this.#start); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.js.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c179a3fdc1cb846d990daa8636b240085d8f8142 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAa,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAkDxD,sDAAs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AC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAA;QAC7D,IAAI,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC3B,gEAAgE;QAChE,6BAA6B;QAC7B,MAAM,GAAG,GAAG,KAAK,KAAK,CAAC,CAAA;QACvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,IAAI;gBAAE,OAAO,KAAK,CAAA;YACxB,MAAM,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;YAC5D,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAE,CAAC,CAAA;QAC/C,CAAC;QACD,OAAO,CAAC,CAAC,KAAK,CAAA;IAChB,CAAC;IAED,8CAA8C;IAC9C,QAAQ;QACN,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IAC1B,CAAC;CACF","sourcesContent":["import { numericRange } from './numeric-range.js'\nimport { type Form, parseClass } from './parse-class.js'\n\nexport type { Form }\n\nexport type MatcherOptions = {\n /** perform a case-insensitive match */\n nocase?: boolean\n /** do not treat strings starting with `.` specially */\n dot?: boolean\n /** do not match extglobs (treat them as normal strings) */\n noext?: boolean\n /**\n * normalize unicode in the pattern and the tested strings, with\n * this form. `true` means `'NFC'`.\n */\n normalize?: boolean | Form\n /**\n * A char that marks a numeric range in the pattern, as\n * `..`, where `lo` and `hi` are integers. It\n * matches the strings that the bash brace expansion `{..}`\n * makes, such as `{1..100}` or `{001..100}`, without making each\n * one. A mark is never escaped by a `\\` before it. Inside a `[...]`\n * class, a mark is a char of the class.\n */\n rangeMark?: string\n}\n\n// parsed pattern items\nexport type Item =\n | { t: 'lit'; ch: string }\n | { t: 'any' | 'star' }\n | { t: 'class'; re: RegExp }\n | { t: 'ext'; type: string; alts: Item[][] }\n\n// extglob syntax tokens become literals if they are not part of a\n// closed extglob\nexport type Token =\n Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' }\n\n// state machine nodes\nexport type NegNode = { t: 'neg'; id: number; sub: Node; next: Node }\nexport type SplitNode = { t: 'split'; id: number; out: Node[] }\nexport type Node =\n | ({ t: 'lit'; id: number; next: Node } & Lit)\n | { t: 'any' | 'star'; id: number; next: Node }\n | { t: 'class'; id: number; re: RegExp; next: Node }\n | SplitNode\n | NegNode\n | { t: 'match'; id: number }\n\n// the end of the pattern, or of a negated sub-pattern\nconst MATCH: Node = { t: 'match', id: 0 }\n\nconst extTypes = '!?+*@'\n\nconst lit = (ch: string): Item => ({ t: 'lit', ch })\n\nconst reEscape = (s: string) => s.replace(/[\\\\^$.*+?()[\\]{}|/]/g, '\\\\$&')\n\n// a RegExp that only matches `s`, with unicode case folding\nconst newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu')\n\n// foldRe for one literal char. The same chars are in most patterns,\n// so keep them. A RegExp without the `g` or `y` flag has no state to\n// share.\nconst foldCache = new Map()\nconst foldRe = (ch: string) => {\n let re = foldCache.get(ch)\n if (!re) {\n re = newFoldRe(ch)\n if (foldCache.size >= 1000) foldCache.clear()\n foldCache.set(ch, re)\n }\n return re\n}\n\n/**\n * A literal char. With `nocase:true`, `re` folds case, and `ascii`\n * holds its results for ASCII chars, by char code: 1 for a match,\n * and 2 for not.\n */\nexport type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array }\n\nconst litMatch = (l: Lit, c: string) => {\n if (c === l.ch) return true\n if (!l.re) return false\n const code = c.charCodeAt(0)\n if (code >= 128) return l.re.test(c)\n const ascii = (l.ascii ??= new Uint8Array(128))\n ascii[code] ||= l.re.test(c) ? 1 : 2\n return ascii[code] === 1\n}\n\nconst tokenize = (\n p: string,\n nocase: boolean,\n noext: boolean,\n form?: Form,\n mark?: string,\n) => {\n const toks: Token[] = []\n for (let i = 0; i < p.length;) {\n const c = String.fromCodePoint(p.codePointAt(i)!)\n if (mark) {\n // a \\ before a range would only escape its first char\n const m = c === '\\\\' && p.startsWith(mark, i + 1) ? 1 : 0\n if (m || c === mark) {\n const start = i + m + mark.length\n const end = p.indexOf(mark, start)\n const r = /^(-?\\d+)\\.\\.(-?\\d+)$/.exec(p.slice(start, end))\n const alts = end !== -1 && r && numericRange(r[1]!, r[2]!)\n if (alts) {\n toks.push({ t: 'ext', type: '@', alts })\n i = end + mark.length\n continue\n }\n }\n }\n if (c === '\\\\') {\n // a trailing \\ is a literal \\\n const e = p.codePointAt(i + 1)\n const ch = e === undefined ? c : String.fromCodePoint(e)\n toks.push(lit(ch))\n i += 1 + ch.length\n continue\n }\n if (c === '[') {\n const [re, consumed] = parseClass(p, i, nocase, form)\n if (consumed) {\n toks.push({ t: 'class', re })\n i += consumed\n continue\n }\n }\n if (!noext && extTypes.includes(c) && p[i + 1] === '(') {\n toks.push({ t: 'open', type: c })\n i += 2\n continue\n }\n toks.push(\n !noext && c === '|' ? { t: 'bar' }\n : !noext && c === ')' ? { t: 'close' }\n : c === '*' ? { t: 'star' }\n : c === '?' ? { t: 'any' }\n : lit(c),\n )\n i += c.length\n }\n return toks\n}\n\n// map each open token index to the index of its close token\nconst pair = (toks: Token[]) => {\n const pairs = new Map()\n const stack: number[] = []\n toks.forEach((tok, i) => {\n if (tok.t === 'open') stack.push(i)\n else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i)\n })\n return pairs\n}\n\n// build the alternatives between start and end. An open token that\n// is not closed is never inside a closed extglob, so bar and close\n// tokens are only literal at the top level.\nconst build = (\n toks: Token[],\n pairs: Map,\n start: number,\n end: number,\n top: boolean,\n): Item[][] => {\n let seq: Item[] = []\n const alts = [seq]\n for (let i = start; i < end; i++) {\n const tok = toks[i]!\n const close = pairs.get(i)\n if (tok.t === 'open' && close !== undefined) {\n const sub = build(toks, pairs, i + 1, close, false)\n seq.push({ t: 'ext', type: tok.type, alts: sub })\n i = close\n } else if (tok.t === 'bar' && !top) {\n alts.push((seq = []))\n } else if (tok.t === 'open') {\n seq.push(lit(tok.type), lit('('))\n } else if (tok.t === 'bar') {\n seq.push(lit('|'))\n } else if (tok.t === 'close') {\n seq.push(lit(')'))\n } else {\n seq.push(tok)\n }\n }\n return alts\n}\n\n// normalize each run of literal chars as one string, so that a char\n// and the combining marks after it compose (or decompose) together.\n// Syntax is already parsed, so a char that normalizes to a syntax\n// char (such as full-width `*` in NFKC) stays a literal.\nconst normalize = (items: Item[], form: Form): Item[] => {\n const out: Item[] = []\n let run = ''\n const flush = () => {\n for (const ch of run.normalize(form)) out.push(lit(ch))\n run = ''\n }\n for (const it of items) {\n if (it.t === 'lit') {\n run += it.ch\n continue\n }\n flush()\n out.push(\n it.t === 'ext' ?\n { ...it, alts: it.alts.map(a => normalize(a, form)) }\n : it,\n )\n }\n flush()\n return out\n}\n\n// the start node, and the number of node ids. Ids are dense, from 0\n// for the match node.\nconst compile = (\n items: Item[],\n nocase: boolean,\n): [start: Node, size: number] => {\n let id = 1\n const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out })\n const seq = (items: Item[], next: Node): Node =>\n items.reduceRight((next, it) => item(it, next), next)\n const item = (it: Item, next: Node): Node => {\n switch (it.t) {\n case 'lit':\n const re = nocase ? foldRe(it.ch) : undefined\n return { t: 'lit', id: id++, ch: it.ch, re, next }\n case 'any':\n case 'star':\n return { t: it.t, id: id++, next }\n case 'class':\n return { t: 'class', id: id++, re: it.re, next }\n }\n const alts = (next: Node) => it.alts.map(a => seq(a, next))\n switch (it.type) {\n case '@':\n return split(alts(next))\n case '?':\n return split([next, ...alts(next)])\n case '!':\n return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }\n }\n // * and +, loop back after each match\n const after = split([])\n const entry = split(alts(after))\n after.out.push(next, entry)\n return it.type === '*' ? after : entry\n }\n const start = seq(items, MATCH)\n return [start, id]\n}\n\n// one line per node, in the order that a walk from the start\n// reaches them. Edges point to node ids. The nodes of a negated\n// sub-pattern are indented under their negation.\nconst show = (start: Node): string => {\n const lines: string[] = []\n const seen = new Set()\n const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id))\n const walk = (n: Node, indent: string) => {\n if (n.t === 'match' || seen.has(n)) return\n seen.add(n)\n const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`)\n switch (n.t) {\n case 'split':\n line(`split -> ${n.out.map(ref).join(', ')}`)\n for (const o of n.out) walk(o, indent)\n return\n case 'neg':\n line(`!(${ref(n.sub)}) -> ${ref(n.next)}`)\n walk(n.sub, indent + ' ')\n return walk(n.next, indent)\n case 'lit':\n line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`)\n break\n case 'class':\n line(`${n.re} -> ${ref(n.next)}`)\n break\n default:\n line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`)\n }\n walk(n.next, indent)\n }\n walk(start, '')\n return [`start -> ${ref(start)}`, ...lines].join('\\n')\n}\n\n// A thread inside a !(...) negation. It holds the threads of the\n// negated sub-pattern, started where the negation started. The\n// negation matches the chars so far if the sub-pattern does not.\ntype Run = { t: 'run'; neg: NegNode; state: State }\n\n// The threads at one position in the string. Each node thread is\n// only kept once, and runs with the same state are only kept once,\n// so that identical threads merge. The match node is not in\n// `threads`, because it can not step. It sets `match` instead.\nclass State {\n // set by the Sim, to mark the nodes that this state has\n gen: number\n threads: Node[] = []\n match = false\n runs: Run[] = []\n // the sorted ids of the threads, with 0 for a match, once the\n // state is done\n ids: number[] = []\n\n constructor(gen: number) {\n this.gen = gen\n }\n\n // no threads, so nothing more can match\n get dead() {\n return !this.threads.length && !this.match && !this.runs.length\n }\n}\n\n// true if the two states hold the same threads\nconst sameState = (a: State, b: State): boolean => {\n if (a.ids.length !== b.ids.length) return false\n if (a.runs.length !== b.runs.length) return false\n if (a.ids.some((id, i) => id !== b.ids[i])) return false\n return a.runs.every(r =>\n b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)),\n )\n}\n\n/**\n * For each node id, the gen of the last state that has the node as\n * a thread, and of the last state that walked through it. A state is\n * built to the end before the states around it go on, and the nodes\n * of a negated sub-pattern are only in its states (other than the\n * match node, which is never marked). So one mark for each node is\n * enough to know if the state being built has it. The Sims of a\n * matcher never run at the same time, so they share one Marks.\n */\nexport type Marks = { has: Float64Array; seen: Float64Array; gen: number }\n\nconst marks = (size: number): Marks => ({\n has: new Float64Array(size),\n seen: new Float64Array(size),\n gen: 0,\n})\n\nclass Sim {\n // `.` and `..` only match literal dots, even with `dot:true`\n dots: boolean\n // the string starts with `.`, and `dot:true` is not set\n dotStart: boolean\n #marks: Marks\n\n constructor(dots: boolean, dotStart: boolean, marks: Marks) {\n this.dots = dots\n this.dotStart = dotStart\n this.#marks = marks\n }\n\n state() {\n return new State(++this.#marks.gen)\n }\n\n // sort the ids of a state, once it has all of its threads\n done(state: State) {\n state.ids = state.threads.map(n => n.id).sort((a, b) => a - b)\n if (state.match) state.ids.unshift(MATCH.id)\n return state\n }\n\n // true the first time that the state walks through the node, so\n // that loops in the graph stop\n #visit(state: State, node: Node) {\n const { seen } = this.#marks\n if (seen[node.id] === state.gen) return false\n seen[node.id] = state.gen\n return true\n }\n\n #addThread(state: State, node: Node) {\n const { has } = this.#marks\n if (has[node.id] === state.gen) return false\n has[node.id] = state.gen\n state.threads.push(node)\n return true\n }\n\n // wildcards only match a leading dot if `dot:true`. In a negated\n // sub-pattern, this does not apply, because the negation itself\n // can not match a leading dot.\n restricted(i: number, top: boolean) {\n return top && (this.dots || (this.dotStart && i === 0))\n }\n\n add(state: State, node: Node, i: number, top: boolean): void {\n switch (node.t) {\n case 'split':\n if (!this.#visit(state, node)) return\n for (const o of node.out) this.add(state, o, i, top)\n return\n case 'neg':\n if (!this.#visit(state, node)) return\n const sub = this.state()\n this.add(sub, node.sub, i, false)\n this.done(sub)\n return this.addRun(\n state,\n { t: 'run', neg: node, state: sub },\n i,\n top,\n )\n case 'star':\n // a * can not start a dotfile, even if it matches nothing\n if (this.restricted(i, top)) return\n if (this.#addThread(state, node))\n this.add(state, node.next, i, top)\n return\n case 'match':\n state.match = true\n return\n default:\n this.#addThread(state, node)\n }\n }\n\n addRun(state: State, run: Run, i: number, top: boolean) {\n for (const r of state.runs) {\n if (r.neg === run.neg && sameState(r.state, run.state)) return\n }\n state.runs.push(run)\n if (!run.state.match) {\n this.add(state, run.neg.next, i, top)\n }\n }\n\n // the threads after char `c`, at index `i`\n step(state: State, c: string, i: number, top: boolean): State {\n const next = this.state()\n for (const th of state.threads) {\n switch (th.t) {\n case 'lit':\n if (litMatch(th, c)) {\n this.add(next, th.next, i + 1, top)\n }\n break\n case 'any':\n if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top)\n break\n case 'class':\n if (!this.restricted(i, top) && th.re.test(c)) {\n this.add(next, th.next, i + 1, top)\n }\n break\n case 'star':\n if (!this.restricted(i, top)) this.add(next, th, i + 1, top)\n }\n }\n if (!this.restricted(i, top)) {\n for (const run of state.runs) {\n // a sub-pattern with no threads can not match again, so the\n // run stays the same\n if (run.state.dead) {\n this.addRun(next, run, i + 1, top)\n continue\n }\n const sub = this.step(run.state, c, i, false)\n this.addRun(\n next,\n { t: 'run', neg: run.neg, state: sub },\n i + 1,\n top,\n )\n }\n }\n return this.done(next)\n }\n}\n\n// A canonical key for the threads in a state. States with the same\n// key hold the same threads, so they match the same strings.\nconst stateKey = (state: State): string => {\n const ids = state.ids.join()\n if (!state.runs.length) return ids\n const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`)\n return `${ids}|${runs.sort().join('|')}`\n}\n\n// A cached state of the simulation, and the states that each char\n// leads to.\ntype DState = {\n state: State\n match: boolean\n // no threads, so nothing more can match\n dead: boolean\n // the next state for each ASCII char, by char code, and for the\n // other chars\n ascii?: (DState | undefined)[]\n next: Map\n}\n\n// The cache can hold about this many chars of state keys and\n// transitions. When it is full, it is cleared, so that a pattern\n// can not use an unbounded amount of memory.\nconst DFA_BUDGET = 1 << 18\n\n// A cache of the states that the simulation reaches, built as the\n// matcher is used. Each char of a string is then one Map lookup,\n// once the states that it leads to are known.\n//\n// The dot rules only restrict the first char of a dotfile (strings\n// that are only `.` or `..` do not use the cache). So a dotfile\n// starts at its own state, which takes its first step with the\n// restriction, and every other state takes steps without it.\nclass Dfa {\n #start: Node\n #states = new Map()\n #size = 0\n #plain?: DState\n #dotStart?: DState\n #sim: Sim\n #dotSim: Sim\n\n constructor(start: Node, marks: Marks) {\n this.#start = start\n this.#sim = new Sim(false, false, marks)\n this.#dotSim = new Sim(false, true, marks)\n }\n\n #make(state: State): DState {\n return {\n state,\n match: state.match,\n dead: state.dead,\n next: new Map(),\n }\n }\n\n #intern(state: State): DState {\n const key = stateKey(state)\n const found = this.#states.get(key)\n if (found) return found\n if (this.#size > DFA_BUDGET) this.#clear()\n const d = this.#make(state)\n this.#states.set(key, d)\n this.#size += key.length + 1\n return d\n }\n\n #clear() {\n this.#states.clear()\n this.#size = 0\n this.#plain = undefined\n this.#dotStart = undefined\n }\n\n start(dotStart: boolean): DState {\n if (dotStart) {\n if (this.#dotStart) return this.#dotStart\n const state = this.#dotSim.state()\n this.#dotSim.add(state, this.#start, 0, true)\n return (this.#dotStart = this.#make(this.#dotSim.done(state)))\n }\n if (this.#plain) return this.#plain\n const state = this.#sim.state()\n this.#sim.add(state, this.#start, 0, true)\n return (this.#plain = this.#intern(this.#sim.done(state)))\n }\n\n // the next state, after a miss in `d.ascii`\n next(d: DState, c: string): DState {\n const code = c.charCodeAt(0)\n const found = code < 128 ? undefined : d.next.get(c)\n if (found) return found\n // the dotfile start is not in the cache, so it is never shared\n const n =\n d === this.#dotStart ?\n this.#intern(this.#dotSim.step(d.state, c, 0, true))\n : this.#intern(this.#sim.step(d.state, c, 1, true))\n if (code < 128) {\n if (!d.ascii) {\n d.ascii = new Array(128)\n this.#size += 128\n }\n d.ascii[code] = n\n } else {\n d.next.set(c, n)\n }\n this.#size++\n return n\n }\n}\n\n/**\n * A node in a graph with no splits or negations. Such a graph is a\n * chain of nodes that each match one char, or a `*`.\n */\nexport type LinearNode = Exclude<\n Node,\n SplitNode | NegNode | { t: 'match' }\n>\n\n// the nodes in order, if the graph is a single chain\nconst linear = (start: Node): LinearNode[] | undefined => {\n const nodes: LinearNode[] = []\n for (let n = start; n.t !== 'match'; n = n.next) {\n if (n.t === 'split' || n.t === 'neg') return undefined\n nodes.push(n)\n }\n return nodes\n}\n\n// Match a chain of nodes. Each node other than `*` matches exactly\n// one char, so on a failure it is enough to go back to the last `*`\n// and let it match one more char. This takes at most\n// nodes.length * chars.length steps.\nconst testLinear = (\n nodes: LinearNode[],\n chars: ArrayLike,\n start: number,\n end: number,\n) => {\n let ni = 0\n let ci = start\n let starNi = -1\n let starCi = 0\n while (ci < end) {\n const n = nodes[ni]\n if (n?.t === 'star') {\n starNi = ni++\n starCi = ci\n continue\n }\n const c = chars[ci]!\n if (\n n &&\n (n.t === 'any' ||\n (n.t === 'lit' && litMatch(n, c)) ||\n (n.t === 'class' && n.re.test(c)))\n ) {\n ni++\n ci++\n continue\n }\n if (starNi === -1) return false\n ni = starNi + 1\n ci = ++starCi\n }\n while (nodes[ni]?.t === 'star') ni++\n return ni === nodes.length\n}\n\n// The least and most chars that the items can match. These are only\n// bounds: a negation can match a string of any length, so it counts\n// as 0 to Infinity.\nconst lengths = (items: Item[]): [min: number, max: number] => {\n let min = 0\n let max = 0\n for (const it of items) {\n const [lo, hi] = itemLengths(it)\n min += lo\n max += hi\n }\n return [min, max]\n}\n\nconst itemLengths = (it: Item): [min: number, max: number] => {\n if (it.t === 'star') return [0, Infinity]\n if (it.t !== 'ext') return [1, 1]\n if (it.type === '!') return [0, Infinity]\n const alts = it.alts.map(lengths)\n const min = Math.min(...alts.map(a => a[0]))\n const max = Math.max(...alts.map(a => a[1]))\n // a loop of alternatives that only match the empty string is empty\n const loop = max === 0 ? 0 : Infinity\n return (\n it.type === '@' ? [min, max]\n : it.type === '?' ? [0, max]\n : it.type === '*' ? [0, loop]\n : [min, loop]\n )\n}\n\n// true if the chars from `start` match the literals\nconst hasAffix = (\n lits: Lit[],\n chars: ArrayLike,\n start: number,\n) => {\n for (let j = 0; j < lits.length; j++) {\n if (!litMatch(lits[j]!, chars[start + j]!)) return false\n }\n return true\n}\n\n// a `/`, or half of a surrogate pair\nconst slashOrSurrogate = /[/\\ud800-\\udfff]/\nconst surrogate = /[\\ud800-\\udfff]/\n\n// a string can be indexed by code point, unless it has surrogate\n// pairs\nconst codePoints = (s: string): ArrayLike =>\n surrogate.test(s) ? [...s] : s\n\nconst noSlash = (s: string) => {\n if (s.includes('/')) {\n throw new Error('can only match a single path portion, got: ' + s)\n }\n}\n\nexport class Matcher {\n pattern: string\n options: MatcherOptions\n #start: Node\n // the number of node ids\n #size: number\n #marks?: Marks\n // the Sim for strings that are only `.` or `..`\n #dotsSim?: Sim\n // the string to compare, if the pattern has no magic. With\n // `nocase:true`, the RegExp that folds case is made when it is\n // first used.\n #literal?: string\n #literalFold = false\n #literalRe?: RegExp\n // the nodes between the prefix and suffix, if the graph is a\n // single chain\n #linear?: LinearNode[]\n // the linear nodes are only `*` and `?`, so the length bounds and\n // the prefix and suffix decide the match\n #wild = false\n // the least and most chars that a match can have\n #min = 0\n #max = Infinity\n // the literals that a match must start and end with. Each one\n // matches exactly one char, and they are distinct items in the\n // pattern, so a string that does not have them can not match.\n #prefix: Lit[] = []\n #suffix: Lit[] = []\n // the prefix and suffix as strings, if they do not fold case\n #prefixStr?: string\n #suffixStr?: string\n // there is a prefix or suffix to check\n #affix = false\n #dfa?: Dfa\n #form?: Form\n\n constructor(pattern: string, options: MatcherOptions = {}) {\n if (pattern.includes('/')) {\n throw new Error(\n 'can only match a single path portion, got pattern: ' + pattern,\n )\n }\n this.pattern = pattern\n this.options = options\n const { nocase = false, noext = false, normalize: n } = options\n this.#form = n === true ? 'NFC' : n || undefined\n // a pattern that is only an empty extglob is a literal string,\n // except for `!()`, which matches any non-empty string\n const literal = /^[?*+@]\\(\\)$/.test(pattern)\n const toks = tokenize(\n pattern,\n nocase,\n noext || literal,\n this.#form,\n options.rangeMark,\n )\n let [items] = build(toks, pair(toks), 0, toks.length, true)\n if (this.#form) items = normalize(items!, this.#form)\n const [start, size] = compile(items!, nocase)\n this.#start = start\n this.#size = size\n if (items!.every(it => it.t === 'lit')) {\n this.#literal = items!.map(it => it.ch).join('')\n this.#literalFold = nocase\n } else {\n const lit = (it: Item): Lit | undefined =>\n it.t !== 'lit' ? undefined\n : nocase ? { ch: it.ch, re: foldRe(it.ch) }\n : { ch: it.ch }\n for (const it of items!) {\n const l = lit(it)\n if (!l) break\n this.#prefix.push(l)\n }\n for (let j = items!.length - 1; j >= 0; j--) {\n const l = lit(items![j]!)\n if (!l) break\n this.#suffix.unshift(l)\n }\n this.#affix = !!(this.#prefix.length || this.#suffix.length)\n if (!nocase) {\n this.#prefixStr = this.#prefix.map(l => l.ch).join('')\n this.#suffixStr = this.#suffix.map(l => l.ch).join('')\n }\n this.#linear = linear(this.#start)?.slice(\n this.#prefix.length,\n -this.#suffix.length || undefined,\n )\n this.#wild = !!this.#linear?.every(\n n => n.t === 'star' || n.t === 'any',\n )\n const [min, max] = lengths(items!)\n this.#min = min\n this.#max = max\n }\n }\n\n test(s: string): boolean {\n // The `/` check uses the string as given, so with normalization it\n // is a separate step. Otherwise, one scan finds both a `/` and the\n // surrogate pairs that stop the string being indexed by code point.\n if (this.#form) {\n noSlash(s)\n return this.#test(s.normalize(this.#form))\n }\n if (slashOrSurrogate.test(s)) {\n noSlash(s)\n return this.#test(s, [...s])\n }\n return this.#test(s, s)\n }\n\n /**\n * The same as {@link Matcher#test}, but the string is not checked\n * for `/` chars, so the result for a string that has one is not\n * defined. Only use it for a string that is known to be one path\n * portion, such as a part of a path that was split on `/`. It can\n * be faster, because some patterns do not need to look at each char\n * of the string.\n */\n testUnchecked(s: string): boolean {\n return this.#test(this.#form ? s.normalize(this.#form) : s)\n }\n\n // Test a string that has no `/`. `chars` indexes it by code point.\n // If it is not given, it is only found if a step needs it.\n #test(s: string, chars?: ArrayLike): boolean {\n if (this.#literal !== undefined) {\n return this.#literalFold ?\n (this.#literalRe ??= newFoldRe(this.#literal)).test(s)\n : s === this.#literal\n }\n // the length check means that the prefix and suffix do not\n // overlap. Without the chars, the length in code points is from\n // half of the UTF-16 length (if each one is a surrogate pair) to\n // all of it, which is often enough to know.\n const min = this.#min\n const max = this.#max\n if (chars === undefined) {\n const most = s.length\n const least = (most + 1) >> 1\n if (most < min || least > max) return false\n if (least < min || most > max) chars = codePoints(s)\n }\n if (\n chars !== undefined &&\n (chars.length < min || chars.length > max)\n ) {\n return false\n }\n const prefix = this.#prefix.length\n if (this.#affix) {\n if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {\n if (\n !s.startsWith(this.#prefixStr) ||\n !s.endsWith(this.#suffixStr)\n ) {\n return false\n }\n } else {\n chars ??= codePoints(s)\n const end = chars.length - this.#suffix.length\n if (\n !hasAffix(this.#prefix, chars, 0) ||\n !hasAffix(this.#suffix, chars, end)\n ) {\n return false\n }\n }\n }\n const dotStart = !this.options.dot && s.startsWith('.')\n if (this.#linear) {\n // `.` and `..` only match literal dots, even with `dot:true`\n if (s === '.' || s === '..') return false\n // only a literal can match the leading dot. A `*` can not\n // start a dotfile, even if it matches nothing.\n if (dotStart && !prefix) return false\n if (this.#wild) return true\n chars ??= codePoints(s)\n const end = chars.length - this.#suffix.length\n return testLinear(this.#linear, chars, prefix, end)\n }\n chars ??= codePoints(s)\n if (s === '.' || s === '..') {\n this.#marks ??= marks(this.#size)\n const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks))\n const start = sim.state()\n sim.add(start, this.#start, 0, true)\n let state = sim.done(start)\n for (let i = 0; i < chars.length; i++) {\n state = sim.step(state, chars[i]!, i, true)\n }\n return state.match\n }\n this.#marks ??= marks(this.#size)\n const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks))\n let d = dfa.start(dotStart)\n // read char codes from the string, so that a one-char string is\n // only made for a cache miss\n const str = chars === s\n for (let i = 0; i < chars.length; i++) {\n if (d.dead) return false\n const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0)\n d = d.ascii?.[code] ?? dfa.next(d, chars[i]!)\n }\n return d.match\n }\n\n /** a readable listing of the state machine */\n toString(): string {\n return show(this.#start)\n }\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.min.js b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.min.js new file mode 100644 index 0000000000000000000000000000000000000000..f4006dfc524f1a245ac9732c08d1e9e513d76b5c --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/index.min.js @@ -0,0 +1,3 @@ +var k=(n,t)=>n===t?{t:"lit",ch:String(n)}:{t:"class",re:new RegExp(`^[${n}-${t}]$`)},b=(n,t)=>t.map(e=>[k(n,n),...e]),y=(n,t)=>{if(!n)return[[]];let e=+n[0],s=+t[0],r=n.slice(1),i=t.slice(1);if(e===s)return b(e,y(r,i));let h="0".repeat(r.length),c="9".repeat(r.length),o=[];r!==h&&o.push(...b(e++,y(r,c)));let u=i===c?[]:b(s--,y(h,i));return e<=s&&o.push([k(e,s),...Array.from(r,()=>k(0,9))]),o.push(...u),o},F=(n,t,e)=>{if(e)return y(String(n).padStart(e,"0"),String(t).padStart(e,"0"));let s=[];for(let r=String(n).length;r<=String(t).length;r++){let i=Math.max(n,r===1?0:10**(r-1)),h=Math.min(t,10**r-1);s.push(...y(String(i),String(h)))}return s},L=(n,t)=>{let e=Number(n),s=Number(t);if(!Number.isSafeInteger(e)||!Number.isSafeInteger(s))return;e>s&&([e,s]=[s,e]);let i=/^-?0\d/.test(n)||/^-?0\d/.test(t)?Math.max(n.length,t.length):0,h=[];if(e<0){let c=F(Math.max(-s,1),-e,i&&i-1);h.push(...c.map(o=>[{t:"lit",ch:"-"},...o]))}return s>=0&&h.push(...F(Math.max(e,0),s,i)),h};var _={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},$=n=>n.replace(/[[\]\\-]/g,"\\$&"),M=/$./,W=(n,t,e=!1,s)=>{let r=g=>{let m=s?g.normalize(s):g;return[...m].length===1?m:g},i=t;if(n.charAt(i)!=="[")throw new Error("not in a brace expression");let h=[],c=[],o=i+1,u=!1,a=!1,l=!1,d=i,p="";t:for(;op.codePointAt(0)?h.push($(p)+"-"+$(m)):m===p&&h.push($(m)),p="",o+=g.length;continue}if(n.startsWith("-]",o+g.length)){h.push($(m+"-")),o+=g.length+1;continue}if(n.startsWith("-",o+g.length)){p=m,o+=g.length+1;continue}h.push($(m)),o+=g.length}if(d({t:"lit",ch:n}),V=n=>n.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),U=n=>new RegExp(`^${V(n)}$`,"iu"),A=new Map,Z=n=>{let t=A.get(n);return t||(t=U(n),A.size>=1e3&&A.clear(),A.set(n,t)),t},P=(n,t)=>{if(t===n.ch)return!0;if(!n.re)return!1;let e=t.charCodeAt(0);if(e>=128)return n.re.test(t);let s=n.ascii??=new Uint8Array(128);return s[e]||=n.re.test(t)?1:2,s[e]===1},X=(n,t,e,s,r)=>{let i=[];for(let h=0;h{let t=new Map,e=[];return n.forEach((s,r)=>{s.t==="open"?e.push(r):s.t==="close"&&e.length&&t.set(e.pop(),r)}),t},q=(n,t,e,s,r)=>{let i=[],h=[i];for(let c=e;c{let e=[],s="",r=()=>{for(let i of s.normalize(t))e.push(w(i));s=""};for(let i of n){if(i.t==="lit"){s+=i.ch;continue}r(),e.push(i.t==="ext"?{...i,alts:i.alts.map(h=>B(h,t))}:i)}return r(),e},tt=(n,t)=>{let e=1,s=c=>({t:"split",id:e++,out:c}),r=(c,o)=>c.reduceRight((u,a)=>i(a,u),o),i=(c,o)=>{switch(c.t){case"lit":let d=t?Z(c.ch):void 0;return{t:"lit",id:e++,ch:c.ch,re:d,next:o};case"any":case"star":return{t:c.t,id:e++,next:o};case"class":return{t:"class",id:e++,re:c.re,next:o}}let u=d=>c.alts.map(p=>r(p,d));switch(c.type){case"@":return s(u(o));case"?":return s([o,...u(o)]);case"!":return{t:"neg",id:e++,sub:s(u(N)),next:o}}let a=s([]),l=s(u(a));return a.out.push(o,l),c.type==="*"?a:l};return[r(n,N),e]},et=n=>{let t=[],e=new Set,s=i=>i.t==="match"?"match":String(i.id),r=(i,h)=>{if(i.t==="match"||e.has(i))return;e.add(i);let c=o=>t.push(`${h}${i.id}: ${o}`);switch(i.t){case"split":c(`split -> ${i.out.map(s).join(", ")}`);for(let o of i.out)r(o,h);return;case"neg":return c(`!(${s(i.sub)}) -> ${s(i.next)}`),r(i.sub,h+" "),r(i.next,h);case"lit":c(`${JSON.stringify(i.ch)} -> ${s(i.next)}`);break;case"class":c(`${i.re} -> ${s(i.next)}`);break;default:c(`${i.t==="any"?"?":"*"} -> ${s(i.next)}`)}r(i.next,h)};return r(n,""),[`start -> ${s(n)}`,...t].join(` +`)},R=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(t){this.gen=t}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},D=(n,t)=>n.ids.length!==t.ids.length||n.runs.length!==t.runs.length||n.ids.some((e,s)=>e!==t.ids[s])?!1:n.runs.every(e=>t.runs.some(s=>s.neg===e.neg&&D(s.state,e.state))),I=n=>({has:new Float64Array(n),seen:new Float64Array(n),gen:0}),S=class{dots;dotStart;#t;constructor(t,e,s){this.dots=t,this.dotStart=e,this.#t=s}state(){return new R(++this.#t.gen)}done(t){return t.ids=t.threads.map(e=>e.id).sort((e,s)=>e-s),t.match&&t.ids.unshift(N.id),t}#s(t,e){let{seen:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,!0)}#e(t,e){let{has:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,t.threads.push(e),!0)}restricted(t,e){return e&&(this.dots||this.dotStart&&t===0)}add(t,e,s,r){switch(e.t){case"split":if(!this.#s(t,e))return;for(let h of e.out)this.add(t,h,s,r);return;case"neg":if(!this.#s(t,e))return;let i=this.state();return this.add(i,e.sub,s,!1),this.done(i),this.addRun(t,{t:"run",neg:e,state:i},s,r);case"star":if(this.restricted(s,r))return;this.#e(t,e)&&this.add(t,e.next,s,r);return;case"match":t.match=!0;return;default:this.#e(t,e)}}addRun(t,e,s,r){for(let i of t.runs)if(i.neg===e.neg&&D(i.state,e.state))return;t.runs.push(e),e.state.match||this.add(t,e.neg.next,s,r)}step(t,e,s,r){let i=this.state();for(let h of t.threads)switch(h.t){case"lit":P(h,e)&&this.add(i,h.next,s+1,r);break;case"any":this.restricted(s,r)||this.add(i,h.next,s+1,r);break;case"class":!this.restricted(s,r)&&h.re.test(e)&&this.add(i,h.next,s+1,r);break;case"star":this.restricted(s,r)||this.add(i,h,s+1,r)}if(!this.restricted(s,r))for(let h of t.runs){if(h.state.dead){this.addRun(i,h,s+1,r);continue}let c=this.step(h.state,e,s,!1);this.addRun(i,{t:"run",neg:h.neg,state:c},s+1,r)}return this.done(i)}},G=n=>{let t=n.ids.join();if(!n.runs.length)return t;let e=n.runs.map(s=>`${s.neg.id}(${G(s.state)})`);return`${t}|${e.sort().join("|")}`},st=1<<18,j=class{#t;#s=new Map;#e=0;#a;#n;#i;#o;constructor(t,e){this.#t=t,this.#i=new S(!1,!1,e),this.#o=new S(!1,!0,e)}#h(t){return{state:t,match:t.match,dead:t.dead,next:new Map}}#u(t){let e=G(t),s=this.#s.get(e);if(s)return s;this.#e>st&&this.#f();let r=this.#h(t);return this.#s.set(e,r),this.#e+=e.length+1,r}#f(){this.#s.clear(),this.#e=0,this.#a=void 0,this.#n=void 0}start(t){if(t){if(this.#n)return this.#n;let s=this.#o.state();return this.#o.add(s,this.#t,0,!0),this.#n=this.#h(this.#o.done(s))}if(this.#a)return this.#a;let e=this.#i.state();return this.#i.add(e,this.#t,0,!0),this.#a=this.#u(this.#i.done(e))}next(t,e){let s=e.charCodeAt(0),r=s<128?void 0:t.next.get(e);if(r)return r;let i=t===this.#n?this.#u(this.#o.step(t.state,e,0,!0)):this.#u(this.#i.step(t.state,e,1,!0));return s<128?(t.ascii||(t.ascii=new Array(128),this.#e+=128),t.ascii[s]=i):t.next.set(e,i),this.#e++,i}},nt=n=>{let t=[];for(let e=n;e.t!=="match";e=e.next){if(e.t==="split"||e.t==="neg")return;t.push(e)}return t},it=(n,t,e,s)=>{let r=0,i=e,h=-1,c=0;for(;i{let t=0,e=0;for(let s of n){let[r,i]=rt(s);t+=r,e+=i}return[t,e]},rt=n=>{if(n.t==="star")return[0,1/0];if(n.t!=="ext")return[1,1];if(n.type==="!")return[0,1/0];let t=n.alts.map(H),e=Math.min(...t.map(i=>i[0])),s=Math.max(...t.map(i=>i[1])),r=s===0?0:1/0;return n.type==="@"?[e,s]:n.type==="?"?[0,s]:n.type==="*"?[0,r]:[e,r]},v=(n,t,e)=>{for(let s=0;sht.test(n)?[...n]:n,O=n=>{if(n.includes("/"))throw new Error("can only match a single path portion, got: "+n)},T=class{pattern;options;#t;#s;#e;#a;#n;#i=!1;#o;#h;#u=!1;#f=0;#m=1/0;#l=[];#c=[];#p;#g;#x=!1;#w;#r;constructor(t,e={}){if(t.includes("/"))throw new Error("can only match a single path portion, got pattern: "+t);this.pattern=t,this.options=e;let{nocase:s=!1,noext:r=!1,normalize:i}=e;this.#r=i===!0?"NFC":i||void 0;let h=/^[?*+@]\(\)$/.test(t),c=X(t,s,r||h,this.#r,e.rangeMark),[o]=q(c,Y(c),0,c.length,!0);this.#r&&(o=B(o,this.#r));let[u,a]=tt(o,s);if(this.#t=u,this.#s=a,o.every(l=>l.t==="lit"))this.#n=o.map(l=>l.ch).join(""),this.#i=s;else{let l=f=>f.t!=="lit"?void 0:s?{ch:f.ch,re:Z(f.ch)}:{ch:f.ch};for(let f of o){let x=l(f);if(!x)break;this.#l.push(x)}for(let f=o.length-1;f>=0;f--){let x=l(o[f]);if(!x)break;this.#c.unshift(x)}this.#x=!!(this.#l.length||this.#c.length),s||(this.#p=this.#l.map(f=>f.ch).join(""),this.#g=this.#c.map(f=>f.ch).join("")),this.#h=nt(this.#t)?.slice(this.#l.length,-this.#c.length||void 0),this.#u=!!this.#h?.every(f=>f.t==="star"||f.t==="any");let[d,p]=H(o);this.#f=d,this.#m=p}}test(t){return this.#r?(O(t),this.#d(t.normalize(this.#r))):ot.test(t)?(O(t),this.#d(t,[...t])):this.#d(t,t)}testUnchecked(t){return this.#d(this.#r?t.normalize(this.#r):t)}#d(t,e){if(this.#n!==void 0)return this.#i?(this.#o??=U(this.#n)).test(t):t===this.#n;let s=this.#f,r=this.#m;if(e===void 0){let a=t.length,l=a+1>>1;if(ar)return!1;(lr)&&(e=C(t))}if(e!==void 0&&(e.lengthr))return!1;let i=this.#l.length;if(this.#x)if(this.#p!==void 0&&this.#g!==void 0){if(!t.startsWith(this.#p)||!t.endsWith(this.#g))return!1}else{e??=C(t);let a=e.length-this.#c.length;if(!v(this.#l,e,0)||!v(this.#c,e,a))return!1}let h=!this.options.dot&&t.startsWith(".");if(this.#h){if(t==="."||t===".."||h&&!i)return!1;if(this.#u)return!0;e??=C(t);let a=e.length-this.#c.length;return it(this.#h,e,i,a)}if(e??=C(t),t==="."||t===".."){this.#e??=I(this.#s);let a=this.#a??=new S(!0,!1,this.#e),l=a.state();a.add(l,this.#t,0,!0);let d=a.done(l);for(let p=0;p\n a === b ?\n { t: 'lit', ch: String(a) }\n : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) }\n\nconst prefix = (d: number, alts: Item[][]) =>\n alts.map(s => [digit(d, d), ...s])\n\n// The digit strings from a to b, which have the same length.\nconst fixed = (a: string, b: string): Item[][] => {\n if (!a) return [[]]\n let lo = +a[0]!\n let hi = +b[0]!\n const ra = a.slice(1)\n const rb = b.slice(1)\n if (lo === hi) return prefix(lo, fixed(ra, rb))\n const zeros = '0'.repeat(ra.length)\n const nines = '9'.repeat(ra.length)\n const out: Item[][] = []\n if (ra !== zeros) out.push(...prefix(lo++, fixed(ra, nines)))\n const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb))\n if (lo <= hi) {\n out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))])\n }\n out.push(...last)\n return out\n}\n\n// The numbers from a to b, where 0 <= a <= b. If width is set, each\n// one has leading zeros to make it that many digits.\nconst nonneg = (a: number, b: number, width: number): Item[][] => {\n if (width) {\n return fixed(\n String(a).padStart(width, '0'),\n String(b).padStart(width, '0'),\n )\n }\n const out: Item[][] = []\n for (let len = String(a).length; len <= String(b).length; len++) {\n const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1))\n const hi = Math.min(b, 10 ** len - 1)\n out.push(...fixed(String(lo), String(hi)))\n }\n return out\n}\n\n/**\n * The strings that the bash brace expansion `{lo..hi}` makes, as\n * the alternatives of an `@(...)` extglob. Each one is a sequence of\n * digits and digit classes, so there are only a few of them, even for\n * a large range.\n *\n * If either end has a leading zero, such as `{01..10}`, each number\n * has leading zeros to make it as long as the longer end, counting a\n * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`.\n *\n * Returns undefined if either end is not a safe integer.\n */\nexport const numericRange = (\n loStr: string,\n hiStr: string,\n): Item[][] | undefined => {\n let lo = Number(loStr)\n let hi = Number(hiStr)\n if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) return\n if (lo > hi) [lo, hi] = [hi, lo]\n const padded = /^-?0\\d/.test(loStr) || /^-?0\\d/.test(hiStr)\n const width = padded ? Math.max(loStr.length, hiStr.length) : 0\n const out: Item[][] = []\n if (lo < 0) {\n const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1)\n out.push(...neg.map(s => [{ t: 'lit', ch: '-' } as Item, ...s]))\n }\n if (hi >= 0) out.push(...nonneg(Math.max(lo, 0), hi, width))\n return out\n}\n", "// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n '[:blank:]': ['\\\\p{Zs}\\\\t'],\n '[:cntrl:]': ['\\\\p{Cc}'],\n '[:digit:]': ['\\\\p{Nd}'],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n '[:lower:]': ['\\\\p{Ll}'],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n '[:upper:]': ['\\\\p{Lu}'],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n glob: string,\n position: number,\n nocase: boolean = false,\n form?: Form,\n): ParseClassResult => {\n // normalize one class member, if it stays one code point\n const norm = (c: string) => {\n const n = form ? c.normalize(form) : c\n return [...n].length === 1 ? n : c\n }\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = String.fromCodePoint(glob.codePointAt(i)!)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return [noMatch, glob.length - pos]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n const n = norm(c)\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n } else if (n === rangeStart) {\n ranges.push(braceEscape(n))\n }\n rangeStart = ''\n i += c.length\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + c.length)) {\n ranges.push(braceEscape(n + '-'))\n i += c.length + 1\n continue\n }\n if (glob.startsWith('-', i + c.length)) {\n rangeStart = n\n i += c.length + 1\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(n))\n i += c.length\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return [noMatch, 0]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return [noMatch, glob.length - pos]\n }\n\n const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n const comb =\n '^' +\n (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs)\n\n return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n", "import { numericRange } from './numeric-range.js'\nimport { type Form, parseClass } from './parse-class.js'\n\nexport type { Form }\n\nexport type MatcherOptions = {\n /** perform a case-insensitive match */\n nocase?: boolean\n /** do not treat strings starting with `.` specially */\n dot?: boolean\n /** do not match extglobs (treat them as normal strings) */\n noext?: boolean\n /**\n * normalize unicode in the pattern and the tested strings, with\n * this form. `true` means `'NFC'`.\n */\n normalize?: boolean | Form\n /**\n * A char that marks a numeric range in the pattern, as\n * `..`, where `lo` and `hi` are integers. It\n * matches the strings that the bash brace expansion `{..}`\n * makes, such as `{1..100}` or `{001..100}`, without making each\n * one. A mark is never escaped by a `\\` before it. Inside a `[...]`\n * class, a mark is a char of the class.\n */\n rangeMark?: string\n}\n\n// parsed pattern items\nexport type Item =\n | { t: 'lit'; ch: string }\n | { t: 'any' | 'star' }\n | { t: 'class'; re: RegExp }\n | { t: 'ext'; type: string; alts: Item[][] }\n\n// extglob syntax tokens become literals if they are not part of a\n// closed extglob\nexport type Token =\n Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' }\n\n// state machine nodes\nexport type NegNode = { t: 'neg'; id: number; sub: Node; next: Node }\nexport type SplitNode = { t: 'split'; id: number; out: Node[] }\nexport type Node =\n | ({ t: 'lit'; id: number; next: Node } & Lit)\n | { t: 'any' | 'star'; id: number; next: Node }\n | { t: 'class'; id: number; re: RegExp; next: Node }\n | SplitNode\n | NegNode\n | { t: 'match'; id: number }\n\n// the end of the pattern, or of a negated sub-pattern\nconst MATCH: Node = { t: 'match', id: 0 }\n\nconst extTypes = '!?+*@'\n\nconst lit = (ch: string): Item => ({ t: 'lit', ch })\n\nconst reEscape = (s: string) => s.replace(/[\\\\^$.*+?()[\\]{}|/]/g, '\\\\$&')\n\n// a RegExp that only matches `s`, with unicode case folding\nconst newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu')\n\n// foldRe for one literal char. The same chars are in most patterns,\n// so keep them. A RegExp without the `g` or `y` flag has no state to\n// share.\nconst foldCache = new Map()\nconst foldRe = (ch: string) => {\n let re = foldCache.get(ch)\n if (!re) {\n re = newFoldRe(ch)\n if (foldCache.size >= 1000) foldCache.clear()\n foldCache.set(ch, re)\n }\n return re\n}\n\n/**\n * A literal char. With `nocase:true`, `re` folds case, and `ascii`\n * holds its results for ASCII chars, by char code: 1 for a match,\n * and 2 for not.\n */\nexport type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array }\n\nconst litMatch = (l: Lit, c: string) => {\n if (c === l.ch) return true\n if (!l.re) return false\n const code = c.charCodeAt(0)\n if (code >= 128) return l.re.test(c)\n const ascii = (l.ascii ??= new Uint8Array(128))\n ascii[code] ||= l.re.test(c) ? 1 : 2\n return ascii[code] === 1\n}\n\nconst tokenize = (\n p: string,\n nocase: boolean,\n noext: boolean,\n form?: Form,\n mark?: string,\n) => {\n const toks: Token[] = []\n for (let i = 0; i < p.length;) {\n const c = String.fromCodePoint(p.codePointAt(i)!)\n if (mark) {\n // a \\ before a range would only escape its first char\n const m = c === '\\\\' && p.startsWith(mark, i + 1) ? 1 : 0\n if (m || c === mark) {\n const start = i + m + mark.length\n const end = p.indexOf(mark, start)\n const r = /^(-?\\d+)\\.\\.(-?\\d+)$/.exec(p.slice(start, end))\n const alts = end !== -1 && r && numericRange(r[1]!, r[2]!)\n if (alts) {\n toks.push({ t: 'ext', type: '@', alts })\n i = end + mark.length\n continue\n }\n }\n }\n if (c === '\\\\') {\n // a trailing \\ is a literal \\\n const e = p.codePointAt(i + 1)\n const ch = e === undefined ? c : String.fromCodePoint(e)\n toks.push(lit(ch))\n i += 1 + ch.length\n continue\n }\n if (c === '[') {\n const [re, consumed] = parseClass(p, i, nocase, form)\n if (consumed) {\n toks.push({ t: 'class', re })\n i += consumed\n continue\n }\n }\n if (!noext && extTypes.includes(c) && p[i + 1] === '(') {\n toks.push({ t: 'open', type: c })\n i += 2\n continue\n }\n toks.push(\n !noext && c === '|' ? { t: 'bar' }\n : !noext && c === ')' ? { t: 'close' }\n : c === '*' ? { t: 'star' }\n : c === '?' ? { t: 'any' }\n : lit(c),\n )\n i += c.length\n }\n return toks\n}\n\n// map each open token index to the index of its close token\nconst pair = (toks: Token[]) => {\n const pairs = new Map()\n const stack: number[] = []\n toks.forEach((tok, i) => {\n if (tok.t === 'open') stack.push(i)\n else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i)\n })\n return pairs\n}\n\n// build the alternatives between start and end. An open token that\n// is not closed is never inside a closed extglob, so bar and close\n// tokens are only literal at the top level.\nconst build = (\n toks: Token[],\n pairs: Map,\n start: number,\n end: number,\n top: boolean,\n): Item[][] => {\n let seq: Item[] = []\n const alts = [seq]\n for (let i = start; i < end; i++) {\n const tok = toks[i]!\n const close = pairs.get(i)\n if (tok.t === 'open' && close !== undefined) {\n const sub = build(toks, pairs, i + 1, close, false)\n seq.push({ t: 'ext', type: tok.type, alts: sub })\n i = close\n } else if (tok.t === 'bar' && !top) {\n alts.push((seq = []))\n } else if (tok.t === 'open') {\n seq.push(lit(tok.type), lit('('))\n } else if (tok.t === 'bar') {\n seq.push(lit('|'))\n } else if (tok.t === 'close') {\n seq.push(lit(')'))\n } else {\n seq.push(tok)\n }\n }\n return alts\n}\n\n// normalize each run of literal chars as one string, so that a char\n// and the combining marks after it compose (or decompose) together.\n// Syntax is already parsed, so a char that normalizes to a syntax\n// char (such as full-width `*` in NFKC) stays a literal.\nconst normalize = (items: Item[], form: Form): Item[] => {\n const out: Item[] = []\n let run = ''\n const flush = () => {\n for (const ch of run.normalize(form)) out.push(lit(ch))\n run = ''\n }\n for (const it of items) {\n if (it.t === 'lit') {\n run += it.ch\n continue\n }\n flush()\n out.push(\n it.t === 'ext' ?\n { ...it, alts: it.alts.map(a => normalize(a, form)) }\n : it,\n )\n }\n flush()\n return out\n}\n\n// the start node, and the number of node ids. Ids are dense, from 0\n// for the match node.\nconst compile = (\n items: Item[],\n nocase: boolean,\n): [start: Node, size: number] => {\n let id = 1\n const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out })\n const seq = (items: Item[], next: Node): Node =>\n items.reduceRight((next, it) => item(it, next), next)\n const item = (it: Item, next: Node): Node => {\n switch (it.t) {\n case 'lit':\n const re = nocase ? foldRe(it.ch) : undefined\n return { t: 'lit', id: id++, ch: it.ch, re, next }\n case 'any':\n case 'star':\n return { t: it.t, id: id++, next }\n case 'class':\n return { t: 'class', id: id++, re: it.re, next }\n }\n const alts = (next: Node) => it.alts.map(a => seq(a, next))\n switch (it.type) {\n case '@':\n return split(alts(next))\n case '?':\n return split([next, ...alts(next)])\n case '!':\n return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }\n }\n // * and +, loop back after each match\n const after = split([])\n const entry = split(alts(after))\n after.out.push(next, entry)\n return it.type === '*' ? after : entry\n }\n const start = seq(items, MATCH)\n return [start, id]\n}\n\n// one line per node, in the order that a walk from the start\n// reaches them. Edges point to node ids. The nodes of a negated\n// sub-pattern are indented under their negation.\nconst show = (start: Node): string => {\n const lines: string[] = []\n const seen = new Set()\n const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id))\n const walk = (n: Node, indent: string) => {\n if (n.t === 'match' || seen.has(n)) return\n seen.add(n)\n const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`)\n switch (n.t) {\n case 'split':\n line(`split -> ${n.out.map(ref).join(', ')}`)\n for (const o of n.out) walk(o, indent)\n return\n case 'neg':\n line(`!(${ref(n.sub)}) -> ${ref(n.next)}`)\n walk(n.sub, indent + ' ')\n return walk(n.next, indent)\n case 'lit':\n line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`)\n break\n case 'class':\n line(`${n.re} -> ${ref(n.next)}`)\n break\n default:\n line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`)\n }\n walk(n.next, indent)\n }\n walk(start, '')\n return [`start -> ${ref(start)}`, ...lines].join('\\n')\n}\n\n// A thread inside a !(...) negation. It holds the threads of the\n// negated sub-pattern, started where the negation started. The\n// negation matches the chars so far if the sub-pattern does not.\ntype Run = { t: 'run'; neg: NegNode; state: State }\n\n// The threads at one position in the string. Each node thread is\n// only kept once, and runs with the same state are only kept once,\n// so that identical threads merge. The match node is not in\n// `threads`, because it can not step. It sets `match` instead.\nclass State {\n // set by the Sim, to mark the nodes that this state has\n gen: number\n threads: Node[] = []\n match = false\n runs: Run[] = []\n // the sorted ids of the threads, with 0 for a match, once the\n // state is done\n ids: number[] = []\n\n constructor(gen: number) {\n this.gen = gen\n }\n\n // no threads, so nothing more can match\n get dead() {\n return !this.threads.length && !this.match && !this.runs.length\n }\n}\n\n// true if the two states hold the same threads\nconst sameState = (a: State, b: State): boolean => {\n if (a.ids.length !== b.ids.length) return false\n if (a.runs.length !== b.runs.length) return false\n if (a.ids.some((id, i) => id !== b.ids[i])) return false\n return a.runs.every(r =>\n b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)),\n )\n}\n\n/**\n * For each node id, the gen of the last state that has the node as\n * a thread, and of the last state that walked through it. A state is\n * built to the end before the states around it go on, and the nodes\n * of a negated sub-pattern are only in its states (other than the\n * match node, which is never marked). So one mark for each node is\n * enough to know if the state being built has it. The Sims of a\n * matcher never run at the same time, so they share one Marks.\n */\nexport type Marks = { has: Float64Array; seen: Float64Array; gen: number }\n\nconst marks = (size: number): Marks => ({\n has: new Float64Array(size),\n seen: new Float64Array(size),\n gen: 0,\n})\n\nclass Sim {\n // `.` and `..` only match literal dots, even with `dot:true`\n dots: boolean\n // the string starts with `.`, and `dot:true` is not set\n dotStart: boolean\n #marks: Marks\n\n constructor(dots: boolean, dotStart: boolean, marks: Marks) {\n this.dots = dots\n this.dotStart = dotStart\n this.#marks = marks\n }\n\n state() {\n return new State(++this.#marks.gen)\n }\n\n // sort the ids of a state, once it has all of its threads\n done(state: State) {\n state.ids = state.threads.map(n => n.id).sort((a, b) => a - b)\n if (state.match) state.ids.unshift(MATCH.id)\n return state\n }\n\n // true the first time that the state walks through the node, so\n // that loops in the graph stop\n #visit(state: State, node: Node) {\n const { seen } = this.#marks\n if (seen[node.id] === state.gen) return false\n seen[node.id] = state.gen\n return true\n }\n\n #addThread(state: State, node: Node) {\n const { has } = this.#marks\n if (has[node.id] === state.gen) return false\n has[node.id] = state.gen\n state.threads.push(node)\n return true\n }\n\n // wildcards only match a leading dot if `dot:true`. In a negated\n // sub-pattern, this does not apply, because the negation itself\n // can not match a leading dot.\n restricted(i: number, top: boolean) {\n return top && (this.dots || (this.dotStart && i === 0))\n }\n\n add(state: State, node: Node, i: number, top: boolean): void {\n switch (node.t) {\n case 'split':\n if (!this.#visit(state, node)) return\n for (const o of node.out) this.add(state, o, i, top)\n return\n case 'neg':\n if (!this.#visit(state, node)) return\n const sub = this.state()\n this.add(sub, node.sub, i, false)\n this.done(sub)\n return this.addRun(\n state,\n { t: 'run', neg: node, state: sub },\n i,\n top,\n )\n case 'star':\n // a * can not start a dotfile, even if it matches nothing\n if (this.restricted(i, top)) return\n if (this.#addThread(state, node))\n this.add(state, node.next, i, top)\n return\n case 'match':\n state.match = true\n return\n default:\n this.#addThread(state, node)\n }\n }\n\n addRun(state: State, run: Run, i: number, top: boolean) {\n for (const r of state.runs) {\n if (r.neg === run.neg && sameState(r.state, run.state)) return\n }\n state.runs.push(run)\n if (!run.state.match) {\n this.add(state, run.neg.next, i, top)\n }\n }\n\n // the threads after char `c`, at index `i`\n step(state: State, c: string, i: number, top: boolean): State {\n const next = this.state()\n for (const th of state.threads) {\n switch (th.t) {\n case 'lit':\n if (litMatch(th, c)) {\n this.add(next, th.next, i + 1, top)\n }\n break\n case 'any':\n if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top)\n break\n case 'class':\n if (!this.restricted(i, top) && th.re.test(c)) {\n this.add(next, th.next, i + 1, top)\n }\n break\n case 'star':\n if (!this.restricted(i, top)) this.add(next, th, i + 1, top)\n }\n }\n if (!this.restricted(i, top)) {\n for (const run of state.runs) {\n // a sub-pattern with no threads can not match again, so the\n // run stays the same\n if (run.state.dead) {\n this.addRun(next, run, i + 1, top)\n continue\n }\n const sub = this.step(run.state, c, i, false)\n this.addRun(\n next,\n { t: 'run', neg: run.neg, state: sub },\n i + 1,\n top,\n )\n }\n }\n return this.done(next)\n }\n}\n\n// A canonical key for the threads in a state. States with the same\n// key hold the same threads, so they match the same strings.\nconst stateKey = (state: State): string => {\n const ids = state.ids.join()\n if (!state.runs.length) return ids\n const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`)\n return `${ids}|${runs.sort().join('|')}`\n}\n\n// A cached state of the simulation, and the states that each char\n// leads to.\ntype DState = {\n state: State\n match: boolean\n // no threads, so nothing more can match\n dead: boolean\n // the next state for each ASCII char, by char code, and for the\n // other chars\n ascii?: (DState | undefined)[]\n next: Map\n}\n\n// The cache can hold about this many chars of state keys and\n// transitions. When it is full, it is cleared, so that a pattern\n// can not use an unbounded amount of memory.\nconst DFA_BUDGET = 1 << 18\n\n// A cache of the states that the simulation reaches, built as the\n// matcher is used. Each char of a string is then one Map lookup,\n// once the states that it leads to are known.\n//\n// The dot rules only restrict the first char of a dotfile (strings\n// that are only `.` or `..` do not use the cache). So a dotfile\n// starts at its own state, which takes its first step with the\n// restriction, and every other state takes steps without it.\nclass Dfa {\n #start: Node\n #states = new Map()\n #size = 0\n #plain?: DState\n #dotStart?: DState\n #sim: Sim\n #dotSim: Sim\n\n constructor(start: Node, marks: Marks) {\n this.#start = start\n this.#sim = new Sim(false, false, marks)\n this.#dotSim = new Sim(false, true, marks)\n }\n\n #make(state: State): DState {\n return {\n state,\n match: state.match,\n dead: state.dead,\n next: new Map(),\n }\n }\n\n #intern(state: State): DState {\n const key = stateKey(state)\n const found = this.#states.get(key)\n if (found) return found\n if (this.#size > DFA_BUDGET) this.#clear()\n const d = this.#make(state)\n this.#states.set(key, d)\n this.#size += key.length + 1\n return d\n }\n\n #clear() {\n this.#states.clear()\n this.#size = 0\n this.#plain = undefined\n this.#dotStart = undefined\n }\n\n start(dotStart: boolean): DState {\n if (dotStart) {\n if (this.#dotStart) return this.#dotStart\n const state = this.#dotSim.state()\n this.#dotSim.add(state, this.#start, 0, true)\n return (this.#dotStart = this.#make(this.#dotSim.done(state)))\n }\n if (this.#plain) return this.#plain\n const state = this.#sim.state()\n this.#sim.add(state, this.#start, 0, true)\n return (this.#plain = this.#intern(this.#sim.done(state)))\n }\n\n // the next state, after a miss in `d.ascii`\n next(d: DState, c: string): DState {\n const code = c.charCodeAt(0)\n const found = code < 128 ? undefined : d.next.get(c)\n if (found) return found\n // the dotfile start is not in the cache, so it is never shared\n const n =\n d === this.#dotStart ?\n this.#intern(this.#dotSim.step(d.state, c, 0, true))\n : this.#intern(this.#sim.step(d.state, c, 1, true))\n if (code < 128) {\n if (!d.ascii) {\n d.ascii = new Array(128)\n this.#size += 128\n }\n d.ascii[code] = n\n } else {\n d.next.set(c, n)\n }\n this.#size++\n return n\n }\n}\n\n/**\n * A node in a graph with no splits or negations. Such a graph is a\n * chain of nodes that each match one char, or a `*`.\n */\nexport type LinearNode = Exclude<\n Node,\n SplitNode | NegNode | { t: 'match' }\n>\n\n// the nodes in order, if the graph is a single chain\nconst linear = (start: Node): LinearNode[] | undefined => {\n const nodes: LinearNode[] = []\n for (let n = start; n.t !== 'match'; n = n.next) {\n if (n.t === 'split' || n.t === 'neg') return undefined\n nodes.push(n)\n }\n return nodes\n}\n\n// Match a chain of nodes. Each node other than `*` matches exactly\n// one char, so on a failure it is enough to go back to the last `*`\n// and let it match one more char. This takes at most\n// nodes.length * chars.length steps.\nconst testLinear = (\n nodes: LinearNode[],\n chars: ArrayLike,\n start: number,\n end: number,\n) => {\n let ni = 0\n let ci = start\n let starNi = -1\n let starCi = 0\n while (ci < end) {\n const n = nodes[ni]\n if (n?.t === 'star') {\n starNi = ni++\n starCi = ci\n continue\n }\n const c = chars[ci]!\n if (\n n &&\n (n.t === 'any' ||\n (n.t === 'lit' && litMatch(n, c)) ||\n (n.t === 'class' && n.re.test(c)))\n ) {\n ni++\n ci++\n continue\n }\n if (starNi === -1) return false\n ni = starNi + 1\n ci = ++starCi\n }\n while (nodes[ni]?.t === 'star') ni++\n return ni === nodes.length\n}\n\n// The least and most chars that the items can match. These are only\n// bounds: a negation can match a string of any length, so it counts\n// as 0 to Infinity.\nconst lengths = (items: Item[]): [min: number, max: number] => {\n let min = 0\n let max = 0\n for (const it of items) {\n const [lo, hi] = itemLengths(it)\n min += lo\n max += hi\n }\n return [min, max]\n}\n\nconst itemLengths = (it: Item): [min: number, max: number] => {\n if (it.t === 'star') return [0, Infinity]\n if (it.t !== 'ext') return [1, 1]\n if (it.type === '!') return [0, Infinity]\n const alts = it.alts.map(lengths)\n const min = Math.min(...alts.map(a => a[0]))\n const max = Math.max(...alts.map(a => a[1]))\n // a loop of alternatives that only match the empty string is empty\n const loop = max === 0 ? 0 : Infinity\n return (\n it.type === '@' ? [min, max]\n : it.type === '?' ? [0, max]\n : it.type === '*' ? [0, loop]\n : [min, loop]\n )\n}\n\n// true if the chars from `start` match the literals\nconst hasAffix = (\n lits: Lit[],\n chars: ArrayLike,\n start: number,\n) => {\n for (let j = 0; j < lits.length; j++) {\n if (!litMatch(lits[j]!, chars[start + j]!)) return false\n }\n return true\n}\n\n// a `/`, or half of a surrogate pair\nconst slashOrSurrogate = /[/\\ud800-\\udfff]/\nconst surrogate = /[\\ud800-\\udfff]/\n\n// a string can be indexed by code point, unless it has surrogate\n// pairs\nconst codePoints = (s: string): ArrayLike =>\n surrogate.test(s) ? [...s] : s\n\nconst noSlash = (s: string) => {\n if (s.includes('/')) {\n throw new Error('can only match a single path portion, got: ' + s)\n }\n}\n\nexport class Matcher {\n pattern: string\n options: MatcherOptions\n #start: Node\n // the number of node ids\n #size: number\n #marks?: Marks\n // the Sim for strings that are only `.` or `..`\n #dotsSim?: Sim\n // the string to compare, if the pattern has no magic. With\n // `nocase:true`, the RegExp that folds case is made when it is\n // first used.\n #literal?: string\n #literalFold = false\n #literalRe?: RegExp\n // the nodes between the prefix and suffix, if the graph is a\n // single chain\n #linear?: LinearNode[]\n // the linear nodes are only `*` and `?`, so the length bounds and\n // the prefix and suffix decide the match\n #wild = false\n // the least and most chars that a match can have\n #min = 0\n #max = Infinity\n // the literals that a match must start and end with. Each one\n // matches exactly one char, and they are distinct items in the\n // pattern, so a string that does not have them can not match.\n #prefix: Lit[] = []\n #suffix: Lit[] = []\n // the prefix and suffix as strings, if they do not fold case\n #prefixStr?: string\n #suffixStr?: string\n // there is a prefix or suffix to check\n #affix = false\n #dfa?: Dfa\n #form?: Form\n\n constructor(pattern: string, options: MatcherOptions = {}) {\n if (pattern.includes('/')) {\n throw new Error(\n 'can only match a single path portion, got pattern: ' + pattern,\n )\n }\n this.pattern = pattern\n this.options = options\n const { nocase = false, noext = false, normalize: n } = options\n this.#form = n === true ? 'NFC' : n || undefined\n // a pattern that is only an empty extglob is a literal string,\n // except for `!()`, which matches any non-empty string\n const literal = /^[?*+@]\\(\\)$/.test(pattern)\n const toks = tokenize(\n pattern,\n nocase,\n noext || literal,\n this.#form,\n options.rangeMark,\n )\n let [items] = build(toks, pair(toks), 0, toks.length, true)\n if (this.#form) items = normalize(items!, this.#form)\n const [start, size] = compile(items!, nocase)\n this.#start = start\n this.#size = size\n if (items!.every(it => it.t === 'lit')) {\n this.#literal = items!.map(it => it.ch).join('')\n this.#literalFold = nocase\n } else {\n const lit = (it: Item): Lit | undefined =>\n it.t !== 'lit' ? undefined\n : nocase ? { ch: it.ch, re: foldRe(it.ch) }\n : { ch: it.ch }\n for (const it of items!) {\n const l = lit(it)\n if (!l) break\n this.#prefix.push(l)\n }\n for (let j = items!.length - 1; j >= 0; j--) {\n const l = lit(items![j]!)\n if (!l) break\n this.#suffix.unshift(l)\n }\n this.#affix = !!(this.#prefix.length || this.#suffix.length)\n if (!nocase) {\n this.#prefixStr = this.#prefix.map(l => l.ch).join('')\n this.#suffixStr = this.#suffix.map(l => l.ch).join('')\n }\n this.#linear = linear(this.#start)?.slice(\n this.#prefix.length,\n -this.#suffix.length || undefined,\n )\n this.#wild = !!this.#linear?.every(\n n => n.t === 'star' || n.t === 'any',\n )\n const [min, max] = lengths(items!)\n this.#min = min\n this.#max = max\n }\n }\n\n test(s: string): boolean {\n // The `/` check uses the string as given, so with normalization it\n // is a separate step. Otherwise, one scan finds both a `/` and the\n // surrogate pairs that stop the string being indexed by code point.\n if (this.#form) {\n noSlash(s)\n return this.#test(s.normalize(this.#form))\n }\n if (slashOrSurrogate.test(s)) {\n noSlash(s)\n return this.#test(s, [...s])\n }\n return this.#test(s, s)\n }\n\n /**\n * The same as {@link Matcher#test}, but the string is not checked\n * for `/` chars, so the result for a string that has one is not\n * defined. Only use it for a string that is known to be one path\n * portion, such as a part of a path that was split on `/`. It can\n * be faster, because some patterns do not need to look at each char\n * of the string.\n */\n testUnchecked(s: string): boolean {\n return this.#test(this.#form ? s.normalize(this.#form) : s)\n }\n\n // Test a string that has no `/`. `chars` indexes it by code point.\n // If it is not given, it is only found if a step needs it.\n #test(s: string, chars?: ArrayLike): boolean {\n if (this.#literal !== undefined) {\n return this.#literalFold ?\n (this.#literalRe ??= newFoldRe(this.#literal)).test(s)\n : s === this.#literal\n }\n // the length check means that the prefix and suffix do not\n // overlap. Without the chars, the length in code points is from\n // half of the UTF-16 length (if each one is a surrogate pair) to\n // all of it, which is often enough to know.\n const min = this.#min\n const max = this.#max\n if (chars === undefined) {\n const most = s.length\n const least = (most + 1) >> 1\n if (most < min || least > max) return false\n if (least < min || most > max) chars = codePoints(s)\n }\n if (\n chars !== undefined &&\n (chars.length < min || chars.length > max)\n ) {\n return false\n }\n const prefix = this.#prefix.length\n if (this.#affix) {\n if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {\n if (\n !s.startsWith(this.#prefixStr) ||\n !s.endsWith(this.#suffixStr)\n ) {\n return false\n }\n } else {\n chars ??= codePoints(s)\n const end = chars.length - this.#suffix.length\n if (\n !hasAffix(this.#prefix, chars, 0) ||\n !hasAffix(this.#suffix, chars, end)\n ) {\n return false\n }\n }\n }\n const dotStart = !this.options.dot && s.startsWith('.')\n if (this.#linear) {\n // `.` and `..` only match literal dots, even with `dot:true`\n if (s === '.' || s === '..') return false\n // only a literal can match the leading dot. A `*` can not\n // start a dotfile, even if it matches nothing.\n if (dotStart && !prefix) return false\n if (this.#wild) return true\n chars ??= codePoints(s)\n const end = chars.length - this.#suffix.length\n return testLinear(this.#linear, chars, prefix, end)\n }\n chars ??= codePoints(s)\n if (s === '.' || s === '..') {\n this.#marks ??= marks(this.#size)\n const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks))\n const start = sim.state()\n sim.add(start, this.#start, 0, true)\n let state = sim.done(start)\n for (let i = 0; i < chars.length; i++) {\n state = sim.step(state, chars[i]!, i, true)\n }\n return state.match\n }\n this.#marks ??= marks(this.#size)\n const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks))\n let d = dfa.start(dotStart)\n // read char codes from the string, so that a one-char string is\n // only made for a cache miss\n const str = chars === s\n for (let i = 0; i < chars.length; i++) {\n if (d.dead) return false\n const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0)\n d = d.ascii?.[code] ?? dfa.next(d, chars[i]!)\n }\n return d.match\n }\n\n /** a readable listing of the state machine */\n toString(): string {\n return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MoB,EAAM6E,EAAM,OAAS,KAAK6B,GAAQ,OACxC,OAAO9B,GAAW,KAAKyB,GAASxB,EAAOyC,EAAQtH,CAAG,CACpD,CAEA,GADA6E,IAAUiB,EAAWlH,CAAC,EAClBA,IAAM,KAAOA,IAAM,KAAM,CAC3B,KAAKmE,KAAWH,EAAM,KAAKmB,EAAK,EAChC,IAAMwD,EAAO,KAAKtB,KAAa,IAAInD,EAAI,GAAM,GAAO,KAAKC,EAAM,EACzDhD,EAAQwH,EAAI,MAAK,EACvBA,EAAI,IAAIxH,EAAO,KAAK8D,GAAQ,EAAG,EAAI,EACnC,IAAIX,EAAQqE,EAAI,KAAKxH,CAAK,EAC1B,QAASF,EAAI,EAAGA,EAAIgF,EAAM,OAAQhF,IAChCqD,EAAQqE,EAAI,KAAKrE,EAAO2B,EAAMhF,CAAC,EAAIA,EAAG,EAAI,EAE5C,OAAOqD,EAAM,KACf,CACA,KAAKH,KAAWH,EAAM,KAAKmB,EAAK,EAChC,IAAMyD,EAAO,KAAKV,KAAS,IAAIlD,EAAI,KAAKC,GAAQ,KAAKd,EAAM,EACvD0B,EAAI+C,EAAI,MAAMvE,CAAQ,EAGpBwE,EAAM5C,IAAUjG,EACtB,QAASiB,EAAI,EAAGA,EAAIgF,EAAM,OAAQhF,IAAK,CACrC,GAAI4E,EAAE,KAAM,MAAO,GACnB,IAAMrF,EAAOqI,EAAM7I,EAAE,WAAWiB,CAAC,EAAIgF,EAAMhF,CAAC,EAAG,WAAW,CAAC,EAC3D4E,EAAIA,EAAE,QAAQrF,CAAI,GAAKoI,EAAI,KAAK/C,EAAGI,EAAMhF,CAAC,CAAE,CAC9C,CACA,OAAO4E,EAAE,KACX,CAGA,UAAQ,CACN,OAAO3C,GAAK,KAAK+B,EAAM,CACzB", + "names": ["digit", "a", "b", "prefix", "d", "alts", "s", "fixed", "lo", "hi", "ra", "rb", "zeros", "nines", "out", "last", "nonneg", "width", "len", "numericRange", "loStr", "hiStr", "neg", "posixClasses", "braceEscape", "s", "noMatch", "parseClass", "glob", "position", "nocase", "form", "norm", "c", "n", "pos", "ranges", "negs", "i", "sawStart", "escaping", "negate", "endPos", "rangeStart", "WHILE", "cls", "unip", "neg", "sranges", "snegs", "comb", "MATCH", "extTypes", "lit", "ch", "reEscape", "s", "newFoldRe", "foldCache", "foldRe", "re", "litMatch", "l", "c", "code", "ascii", "tokenize", "p", "nocase", "noext", "form", "mark", "toks", "i", "m", "start", "end", "r", "alts", "numericRange", "e", "consumed", "parseClass", "pair", "pairs", "stack", "tok", "build", "top", "seq", "close", "sub", "normalize", "items", "out", "run", "flush", "it", "a", "compile", "id", "split", "next", "item", "after", "entry", "show", "lines", "seen", "ref", "n", "walk", "indent", "line", "desc", "State", "gen", "sameState", "b", "o", "marks", "size", "Sim", "#marks", "dots", "dotStart", "state", "#visit", "node", "#addThread", "has", "th", "stateKey", "ids", "runs", "DFA_BUDGET", "Dfa", "#start", "#states", "#size", "#plain", "#dotStart", "#sim", "#dotSim", "#make", "#intern", "key", "found", "#clear", "d", "linear", "nodes", "testLinear", "chars", "ni", "ci", "starNi", "starCi", "lengths", "min", "max", "lo", "hi", "itemLengths", "loop", "hasAffix", "lits", "j", "slashOrSurrogate", "surrogate", "codePoints", "noSlash", "Matcher", "#dotsSim", "#literal", "#literalFold", "#literalRe", "#linear", "#wild", "#min", "#max", "#prefix", "#suffix", "#prefixStr", "#suffixStr", "#affix", "#dfa", "#form", "pattern", "options", "literal", "#test", "most", "least", "prefix", "sim", "dfa", "str"] +} diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.d.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e90c51724be67c053c23facbc3e3ab70f51c3368 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.d.ts @@ -0,0 +1,15 @@ +import type { Item } from './index.js'; +/** + * The strings that the bash brace expansion `{lo..hi}` makes, as + * the alternatives of an `@(...)` extglob. Each one is a sequence of + * digits and digit classes, so there are only a few of them, even for + * a large range. + * + * If either end has a leading zero, such as `{01..10}`, each number + * has leading zeros to make it as long as the longer end, counting a + * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`. + * + * Returns undefined if either end is not a safe integer. + */ +export declare const numericRange: (loStr: string, hiStr: string) => Item[][] | undefined; +//# sourceMappingURL=numeric-range.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.d.ts.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..2e3c35fc58538bed19bdf85b8a5ba977cd2007e7 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"numeric-range.d.ts","sourceRoot":"","sources":["../../src/numeric-range.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAiDtC;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,YAAY,GACvB,OAAO,MAAM,EACb,OAAO,MAAM,KACZ,IAAI,EAAE,EAAE,GAAG,SAcb,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.js b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.js new file mode 100644 index 0000000000000000000000000000000000000000..f2ebdd94dfb04bcba44e5d0566199cebdfcd45b8 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.js @@ -0,0 +1,72 @@ +// One digit, or a class of digits from a to b. +const digit = (a, b) => a === b ? + { t: 'lit', ch: String(a) } + : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) }; +const prefix = (d, alts) => alts.map(s => [digit(d, d), ...s]); +// The digit strings from a to b, which have the same length. +const fixed = (a, b) => { + if (!a) + return [[]]; + let lo = +a[0]; + let hi = +b[0]; + const ra = a.slice(1); + const rb = b.slice(1); + if (lo === hi) + return prefix(lo, fixed(ra, rb)); + const zeros = '0'.repeat(ra.length); + const nines = '9'.repeat(ra.length); + const out = []; + if (ra !== zeros) + out.push(...prefix(lo++, fixed(ra, nines))); + const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb)); + if (lo <= hi) { + out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))]); + } + out.push(...last); + return out; +}; +// The numbers from a to b, where 0 <= a <= b. If width is set, each +// one has leading zeros to make it that many digits. +const nonneg = (a, b, width) => { + if (width) { + return fixed(String(a).padStart(width, '0'), String(b).padStart(width, '0')); + } + const out = []; + for (let len = String(a).length; len <= String(b).length; len++) { + const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1)); + const hi = Math.min(b, 10 ** len - 1); + out.push(...fixed(String(lo), String(hi))); + } + return out; +}; +/** + * The strings that the bash brace expansion `{lo..hi}` makes, as + * the alternatives of an `@(...)` extglob. Each one is a sequence of + * digits and digit classes, so there are only a few of them, even for + * a large range. + * + * If either end has a leading zero, such as `{01..10}`, each number + * has leading zeros to make it as long as the longer end, counting a + * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`. + * + * Returns undefined if either end is not a safe integer. + */ +export const numericRange = (loStr, hiStr) => { + let lo = Number(loStr); + let hi = Number(hiStr); + if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) + return; + if (lo > hi) + [lo, hi] = [hi, lo]; + const padded = /^-?0\d/.test(loStr) || /^-?0\d/.test(hiStr); + const width = padded ? Math.max(loStr.length, hiStr.length) : 0; + const out = []; + if (lo < 0) { + const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1); + out.push(...neg.map(s => [{ t: 'lit', ch: '-' }, ...s])); + } + if (hi >= 0) + out.push(...nonneg(Math.max(lo, 0), hi, width)); + return out; +}; +//# sourceMappingURL=numeric-range.js.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.js.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8433590ebb3a1a21b16c626b2d469e41f9910e35 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/numeric-range.js.map @@ -0,0 +1 @@ +{"version":3,"file":"numeric-range.js","sourceRoot":"","sources":["../../src/numeric-range.ts"],"names":[],"mappings":"AAEA,+CAA+C;AAC/C,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,CAAS,EAAQ,EAAE,CAC3C,CAAC,KAAK,CAAC,CAAC,CAAC;IACP,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE;IAC7B,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAA;AAEnD,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,IAAc,EAAE,EAAE,CAC3C,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAA;AAEpC,6DAA6D;AAC7D,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,CAAS,EAAY,EAAE;IAC/C,IAAI,CAAC,CAAC;QAAE,OAAO,CAAC,EAAE,CAAC,CAAA;IACnB,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAE,CAAA;IACf,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAE,CAAA;IACf,MAAM,EA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A;IAChC,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAC3D,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAC/D,MAAM,GAAG,GAAa,EAAE,CAAA;IACxB,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACX,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,IAAI,KAAK,GAAG,CAAC,CAAC,CAAA;QAC7D,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,GAAG,EAAU,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;IACD,IAAI,EAAE,IAAI,CAAC;QAAE,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC,CAAA;IAC5D,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA","sourcesContent":["import type { Item } from './index.js'\n\n// One digit, or a class of digits from a to b.\nconst digit = (a: number, b: number): Item =>\n a === b ?\n { t: 'lit', ch: String(a) }\n : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) }\n\nconst prefix = (d: number, alts: Item[][]) =>\n alts.map(s => [digit(d, d), ...s])\n\n// The digit strings from a to b, which have the same length.\nconst fixed = (a: string, b: string): Item[][] => {\n if (!a) return [[]]\n let lo = +a[0]!\n let hi = +b[0]!\n const ra = a.slice(1)\n const rb = b.slice(1)\n if (lo === hi) return prefix(lo, fixed(ra, rb))\n const zeros = '0'.repeat(ra.length)\n const nines = '9'.repeat(ra.length)\n const out: Item[][] = []\n if (ra !== zeros) out.push(...prefix(lo++, fixed(ra, nines)))\n const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb))\n if (lo <= hi) {\n out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))])\n }\n out.push(...last)\n return out\n}\n\n// The numbers from a to b, where 0 <= a <= b. If width is set, each\n// one has leading zeros to make it that many digits.\nconst nonneg = (a: number, b: number, width: number): Item[][] => {\n if (width) {\n return fixed(\n String(a).padStart(width, '0'),\n String(b).padStart(width, '0'),\n )\n }\n const out: Item[][] = []\n for (let len = String(a).length; len <= String(b).length; len++) {\n const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1))\n const hi = Math.min(b, 10 ** len - 1)\n out.push(...fixed(String(lo), String(hi)))\n }\n return out\n}\n\n/**\n * The strings that the bash brace expansion `{lo..hi}` makes, as\n * the alternatives of an `@(...)` extglob. Each one is a sequence of\n * digits and digit classes, so there are only a few of them, even for\n * a large range.\n *\n * If either end has a leading zero, such as `{01..10}`, each number\n * has leading zeros to make it as long as the longer end, counting a\n * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`.\n *\n * Returns undefined if either end is not a safe integer.\n */\nexport const numericRange = (\n loStr: string,\n hiStr: string,\n): Item[][] | undefined => {\n let lo = Number(loStr)\n let hi = Number(hiStr)\n if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) return\n if (lo > hi) [lo, hi] = [hi, lo]\n const padded = /^-?0\\d/.test(loStr) || /^-?0\\d/.test(hiStr)\n const width = padded ? Math.max(loStr.length, hiStr.length) : 0\n const out: Item[][] = []\n if (lo < 0) {\n const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1)\n out.push(...neg.map(s => [{ t: 'lit', ch: '-' } as Item, ...s]))\n }\n if (hi >= 0) out.push(...nonneg(Math.max(lo, 0), hi, width))\n return out\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/package.json b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.d.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f0dbca07538fdb8bee4ed70b636da30c5f92b19 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.d.ts @@ -0,0 +1,4 @@ +export type ParseClassResult = [re: RegExp, consumed: number]; +export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'; +export declare const parseClass: (glob: string, position: number, nocase?: boolean, form?: Form) => ParseClassResult; +//# sourceMappingURL=parse-class.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.d.ts.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..9edec7a94af01d9b1c8fcf1471b2548579159b83 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-class.d.ts","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAyBA,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AAE7D,MAAM,MAAM,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAA;AAWlD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,EAChB,SAAQ,OAAe,EACvB,OAAO,IAAI,KACV,gBAkHF,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.js b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.js similarity index 48% rename from mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.js rename to mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.js index 4b49d40bd74210708c8afdee944010ca1023fb83..da90baceba0e0f00363dae6993a0c4f74fe2da6f 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.js +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.js @@ -1,36 +1,39 @@ // translate the various posix character classes into unicode properties // this works across all unicode locales -// { : [, /u flag required, negated] +// { : [, negated] const posixClasses = { - '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], - '[:alpha:]': ['\\p{L}\\p{Nl}', true], - '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], - '[:blank:]': ['\\p{Zs}\\t', true], - '[:cntrl:]': ['\\p{Cc}', true], - '[:digit:]': ['\\p{Nd}', true], - '[:graph:]': ['\\p{Z}\\p{C}', true, true], - '[:lower:]': ['\\p{Ll}', true], + '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'], + '[:alpha:]': ['\\p{L}\\p{Nl}'], + '[:ascii:]': ['\\x' + '00-\\x' + '7f'], + '[:blank:]': ['\\p{Zs}\\t'], + '[:cntrl:]': ['\\p{Cc}'], + '[:digit:]': ['\\p{Nd}'], + '[:graph:]': ['\\p{Z}\\p{C}', true], + '[:lower:]': ['\\p{Ll}'], '[:print:]': ['\\p{C}', true], - '[:punct:]': ['\\p{P}', true], - '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], - '[:upper:]': ['\\p{Lu}', true], - '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], - '[:xdigit:]': ['A-Fa-f0-9', false], + '[:punct:]': ['\\p{P}\\p{S}'], + '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'], + '[:upper:]': ['\\p{Lu}'], + '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'], + '[:xdigit:]': ['A-Fa-f0-9'], }; // only need to escape a few things inside of brace expressions // escapes: [ \ ] - const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); -// escape all regexp magic characters -const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); -// everything has already been escaped, we just have to join -const rangesToString = (ranges) => ranges.join(''); -// takes a glob string at a posix brace expression, and returns -// an equivalent regular expression source, and boolean indicating -// whether the /u flag needs to be applied, and the number of chars -// consumed to parse the character class. -// This also removes out of order ranges, and returns ($.) if the -// entire class just no good. -export const parseClass = (glob, position) => { +const noMatch = /$./; +// Takes a glob string at a posix brace expression. Returns a RegExp +// that tests one character, and the number of glob chars consumed. +// If the class is not closed, consumed is 0, and the `[` must be +// treated as a literal character. +// Out of order ranges are removed. If nothing is left, the RegExp +// is `/$./`, and the rest of the glob is consumed, so that the +// whole glob cannot match. +export const parseClass = (glob, position, nocase = false, form) => { + // normalize one class member, if it stays one code point + const norm = (c) => { + const n = form ? c.normalize(form) : c; + return [...n].length === 1 ? n : c; + }; const pos = position; /* c8 ignore start */ if (glob.charAt(pos) !== '[') { @@ -41,13 +44,12 @@ export const parseClass = (glob, position) => { const negs = []; let i = pos + 1; let sawStart = false; - let uflag = false; let escaping = false; let negate = false; let endPos = pos; let rangeStart = ''; WHILE: while (i < glob.length) { - const c = glob.charAt(i); + const c = String.fromCodePoint(glob.codePointAt(i)); if ((c === '!' || c === '^') && i === pos + 1) { negate = true; i++; @@ -68,79 +70,69 @@ export const parseClass = (glob, position) => { } if (c === '[' && !escaping) { // either a posix class, a collation equivalent, or just a [ - for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { + for (const [cls, [unip, neg]] of Object.entries(posixClasses)) { if (glob.startsWith(cls, i)) { // invalid, [a-[] is fine, but not [a-[:alpha]] if (rangeStart) { - return ['$.', false, glob.length - pos, true]; + return [noMatch, glob.length - pos]; } i += cls.length; if (neg) negs.push(unip); else ranges.push(unip); - uflag = uflag || u; continue WHILE; } } } // now it's just a normal character, effectively escaping = false; + const n = norm(c); if (rangeStart) { // throw this range away if it's not valid, but others // can still match. - if (c > rangeStart) { - ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); + if (n.codePointAt(0) > rangeStart.codePointAt(0)) { + ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n)); } - else if (c === rangeStart) { - ranges.push(braceEscape(c)); + else if (n === rangeStart) { + ranges.push(braceEscape(n)); } rangeStart = ''; - i++; + i += c.length; continue; } // now might be the start of a range. // can be either c-d or c-] or c] or c] at this point - if (glob.startsWith('-]', i + 1)) { - ranges.push(braceEscape(c + '-')); - i += 2; + if (glob.startsWith('-]', i + c.length)) { + ranges.push(braceEscape(n + '-')); + i += c.length + 1; continue; } - if (glob.startsWith('-', i + 1)) { - rangeStart = c; - i += 2; + if (glob.startsWith('-', i + c.length)) { + rangeStart = n; + i += c.length + 1; continue; } // not the start of a range, just a single character - ranges.push(braceEscape(c)); - i++; + ranges.push(braceEscape(n)); + i += c.length; } if (endPos < i) { // didn't see the end of the class, not a valid class, // but might still be valid as a literal match. - return ['', false, 0, false]; + return [noMatch, 0]; } // if we got no ranges and no negates, then we have a range that // cannot possibly match anything, and that poisons the whole glob if (!ranges.length && !negs.length) { - return ['$.', false, glob.length - pos, true]; - } - // if we got one positive range, and it's a single character, then that's - // not actually a magic pattern, it's just that one literal character. - // we should not treat that as "magic", we should just return the literal - // character. [_] is a perfectly valid way to escape glob magic chars. - if (negs.length === 0 && - ranges.length === 1 && - /^\\?.$/.test(ranges[0]) && - !negate) { - const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; - return [regexpEscape(r), false, endPos - pos, false]; + return [noMatch, glob.length - pos]; } - const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; - const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; - const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' - : ranges.length ? sranges - : snegs; - return [comb, uflag, endPos - pos, true]; + const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'; + const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'; + const comb = '^' + + (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' + : ranges.length ? sranges + : snegs); + return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]; }; -//# sourceMappingURL=brace-expressions.js.map \ No newline at end of file +//# sourceMappingURL=parse-class.js.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.js.map b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d3ad1f85de2a19d1849f1207a16ce72714fda94a --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/dist/esm/parse-class.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-class.js","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,wCAAwC;AAExC,4CAA4C;AAC5C,MAAM,YAAY,GAA8C;IAC9D,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,CAAC;IACtC,WAAW,EAAE,CAAC,YAAY,CAAC;IAC3B,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,S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AAM,CAAC,CAAC,CAAC,OAAO;gBACzB,CAAC,CAAC,KAAK,CAAC,CAAA;IAEV,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,CAAA;AAC9D,CAAC,CAAA","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n '[:blank:]': ['\\\\p{Zs}\\\\t'],\n '[:cntrl:]': ['\\\\p{Cc}'],\n '[:digit:]': ['\\\\p{Nd}'],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n '[:lower:]': ['\\\\p{Ll}'],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n '[:upper:]': ['\\\\p{Lu}'],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n glob: string,\n position: number,\n nocase: boolean = false,\n form?: Form,\n): ParseClassResult => {\n // normalize one class member, if it stays one code point\n const norm = (c: string) => {\n const n = form ? c.normalize(form) : c\n return [...n].length === 1 ? n : c\n }\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = String.fromCodePoint(glob.codePointAt(i)!)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return [noMatch, glob.length - pos]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n const n = norm(c)\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n } else if (n === rangeStart) {\n ranges.push(braceEscape(n))\n }\n rangeStart = ''\n i += c.length\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + c.length)) {\n ranges.push(braceEscape(n + '-'))\n i += c.length + 1\n continue\n }\n if (glob.startsWith('-', i + c.length)) {\n rangeStart = n\n i += c.length + 1\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(n))\n i += c.length\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return [noMatch, 0]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return [noMatch, glob.length - pos]\n }\n\n const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n const comb =\n '^' +\n (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs)\n\n return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/package.json b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dd913c6e982849eb035229ebff94c344bf0f1a98 --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/package.json @@ -0,0 +1,56 @@ +{ + "name": "@isaacs/nonrecursive-glob-match", + "description": "a single-path-portion glob matcher not subject to recursive backtracking ReDoS", + "version": "1.1.0", + "license": "BlueOak-1.0.0", + "files": [ + "dist", + "src" + ], + "devDependencies": { + "esbuild": "^0.28.2", + "prettier": "^3.9.10", + "tap": "^21.8.0", + "tshy": "^4.1.3", + "typedoc": "^0.28.20" + }, + "scripts": { + "format": "prettier --write .", + "test": "tap", + "snap": "tap", + "typedoc": "typedoc", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "prepare": "tshy && bash scripts/build.sh", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "type": "module", + "tshy": { + "selfLink": false, + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js", + "allowScripts": { + "esbuild@0.28.2": true + } +} diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/index.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6372c509718520f07f4cfd3cb9b77d323a09c2da --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/index.ts @@ -0,0 +1,932 @@ +import { numericRange } from './numeric-range.js' +import { type Form, parseClass } from './parse-class.js' + +export type { Form } + +export type MatcherOptions = { + /** perform a case-insensitive match */ + nocase?: boolean + /** do not treat strings starting with `.` specially */ + dot?: boolean + /** do not match extglobs (treat them as normal strings) */ + noext?: boolean + /** + * normalize unicode in the pattern and the tested strings, with + * this form. `true` means `'NFC'`. + */ + normalize?: boolean | Form + /** + * A char that marks a numeric range in the pattern, as + * `..`, where `lo` and `hi` are integers. It + * matches the strings that the bash brace expansion `{..}` + * makes, such as `{1..100}` or `{001..100}`, without making each + * one. A mark is never escaped by a `\` before it. Inside a `[...]` + * class, a mark is a char of the class. + */ + rangeMark?: string +} + +// parsed pattern items +export type Item = + | { t: 'lit'; ch: string } + | { t: 'any' | 'star' } + | { t: 'class'; re: RegExp } + | { t: 'ext'; type: string; alts: Item[][] } + +// extglob syntax tokens become literals if they are not part of a +// closed extglob +export type Token = + Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' } + +// state machine nodes +export type NegNode = { t: 'neg'; id: number; sub: Node; next: Node } +export type SplitNode = { t: 'split'; id: number; out: Node[] } +export type Node = + | ({ t: 'lit'; id: number; next: Node } & Lit) + | { t: 'any' | 'star'; id: number; next: Node } + | { t: 'class'; id: number; re: RegExp; next: Node } + | SplitNode + | NegNode + | { t: 'match'; id: number } + +// the end of the pattern, or of a negated sub-pattern +const MATCH: Node = { t: 'match', id: 0 } + +const extTypes = '!?+*@' + +const lit = (ch: string): Item => ({ t: 'lit', ch }) + +const reEscape = (s: string) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&') + +// a RegExp that only matches `s`, with unicode case folding +const newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu') + +// foldRe for one literal char. The same chars are in most patterns, +// so keep them. A RegExp without the `g` or `y` flag has no state to +// share. +const foldCache = new Map() +const foldRe = (ch: string) => { + let re = foldCache.get(ch) + if (!re) { + re = newFoldRe(ch) + if (foldCache.size >= 1000) foldCache.clear() + foldCache.set(ch, re) + } + return re +} + +/** + * A literal char. With `nocase:true`, `re` folds case, and `ascii` + * holds its results for ASCII chars, by char code: 1 for a match, + * and 2 for not. + */ +export type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array } + +const litMatch = (l: Lit, c: string) => { + if (c === l.ch) return true + if (!l.re) return false + const code = c.charCodeAt(0) + if (code >= 128) return l.re.test(c) + const ascii = (l.ascii ??= new Uint8Array(128)) + ascii[code] ||= l.re.test(c) ? 1 : 2 + return ascii[code] === 1 +} + +const tokenize = ( + p: string, + nocase: boolean, + noext: boolean, + form?: Form, + mark?: string, +) => { + const toks: Token[] = [] + for (let i = 0; i < p.length;) { + const c = String.fromCodePoint(p.codePointAt(i)!) + if (mark) { + // a \ before a range would only escape its first char + const m = c === '\\' && p.startsWith(mark, i + 1) ? 1 : 0 + if (m || c === mark) { + const start = i + m + mark.length + const end = p.indexOf(mark, start) + const r = /^(-?\d+)\.\.(-?\d+)$/.exec(p.slice(start, end)) + const alts = end !== -1 && r && numericRange(r[1]!, r[2]!) + if (alts) { + toks.push({ t: 'ext', type: '@', alts }) + i = end + mark.length + continue + } + } + } + if (c === '\\') { + // a trailing \ is a literal \ + const e = p.codePointAt(i + 1) + const ch = e === undefined ? c : String.fromCodePoint(e) + toks.push(lit(ch)) + i += 1 + ch.length + continue + } + if (c === '[') { + const [re, consumed] = parseClass(p, i, nocase, form) + if (consumed) { + toks.push({ t: 'class', re }) + i += consumed + continue + } + } + if (!noext && extTypes.includes(c) && p[i + 1] === '(') { + toks.push({ t: 'open', type: c }) + i += 2 + continue + } + toks.push( + !noext && c === '|' ? { t: 'bar' } + : !noext && c === ')' ? { t: 'close' } + : c === '*' ? { t: 'star' } + : c === '?' ? { t: 'any' } + : lit(c), + ) + i += c.length + } + return toks +} + +// map each open token index to the index of its close token +const pair = (toks: Token[]) => { + const pairs = new Map() + const stack: number[] = [] + toks.forEach((tok, i) => { + if (tok.t === 'open') stack.push(i) + else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i) + }) + return pairs +} + +// build the alternatives between start and end. An open token that +// is not closed is never inside a closed extglob, so bar and close +// tokens are only literal at the top level. +const build = ( + toks: Token[], + pairs: Map, + start: number, + end: number, + top: boolean, +): Item[][] => { + let seq: Item[] = [] + const alts = [seq] + for (let i = start; i < end; i++) { + const tok = toks[i]! + const close = pairs.get(i) + if (tok.t === 'open' && close !== undefined) { + const sub = build(toks, pairs, i + 1, close, false) + seq.push({ t: 'ext', type: tok.type, alts: sub }) + i = close + } else if (tok.t === 'bar' && !top) { + alts.push((seq = [])) + } else if (tok.t === 'open') { + seq.push(lit(tok.type), lit('(')) + } else if (tok.t === 'bar') { + seq.push(lit('|')) + } else if (tok.t === 'close') { + seq.push(lit(')')) + } else { + seq.push(tok) + } + } + return alts +} + +// normalize each run of literal chars as one string, so that a char +// and the combining marks after it compose (or decompose) together. +// Syntax is already parsed, so a char that normalizes to a syntax +// char (such as full-width `*` in NFKC) stays a literal. +const normalize = (items: Item[], form: Form): Item[] => { + const out: Item[] = [] + let run = '' + const flush = () => { + for (const ch of run.normalize(form)) out.push(lit(ch)) + run = '' + } + for (const it of items) { + if (it.t === 'lit') { + run += it.ch + continue + } + flush() + out.push( + it.t === 'ext' ? + { ...it, alts: it.alts.map(a => normalize(a, form)) } + : it, + ) + } + flush() + return out +} + +// the start node, and the number of node ids. Ids are dense, from 0 +// for the match node. +const compile = ( + items: Item[], + nocase: boolean, +): [start: Node, size: number] => { + let id = 1 + const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out }) + const seq = (items: Item[], next: Node): Node => + items.reduceRight((next, it) => item(it, next), next) + const item = (it: Item, next: Node): Node => { + switch (it.t) { + case 'lit': + const re = nocase ? foldRe(it.ch) : undefined + return { t: 'lit', id: id++, ch: it.ch, re, next } + case 'any': + case 'star': + return { t: it.t, id: id++, next } + case 'class': + return { t: 'class', id: id++, re: it.re, next } + } + const alts = (next: Node) => it.alts.map(a => seq(a, next)) + switch (it.type) { + case '@': + return split(alts(next)) + case '?': + return split([next, ...alts(next)]) + case '!': + return { t: 'neg', id: id++, sub: split(alts(MATCH)), next } + } + // * and +, loop back after each match + const after = split([]) + const entry = split(alts(after)) + after.out.push(next, entry) + return it.type === '*' ? after : entry + } + const start = seq(items, MATCH) + return [start, id] +} + +// one line per node, in the order that a walk from the start +// reaches them. Edges point to node ids. The nodes of a negated +// sub-pattern are indented under their negation. +const show = (start: Node): string => { + const lines: string[] = [] + const seen = new Set() + const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id)) + const walk = (n: Node, indent: string) => { + if (n.t === 'match' || seen.has(n)) return + seen.add(n) + const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`) + switch (n.t) { + case 'split': + line(`split -> ${n.out.map(ref).join(', ')}`) + for (const o of n.out) walk(o, indent) + return + case 'neg': + line(`!(${ref(n.sub)}) -> ${ref(n.next)}`) + walk(n.sub, indent + ' ') + return walk(n.next, indent) + case 'lit': + line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`) + break + case 'class': + line(`${n.re} -> ${ref(n.next)}`) + break + default: + line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`) + } + walk(n.next, indent) + } + walk(start, '') + return [`start -> ${ref(start)}`, ...lines].join('\n') +} + +// A thread inside a !(...) negation. It holds the threads of the +// negated sub-pattern, started where the negation started. The +// negation matches the chars so far if the sub-pattern does not. +type Run = { t: 'run'; neg: NegNode; state: State } + +// The threads at one position in the string. Each node thread is +// only kept once, and runs with the same state are only kept once, +// so that identical threads merge. The match node is not in +// `threads`, because it can not step. It sets `match` instead. +class State { + // set by the Sim, to mark the nodes that this state has + gen: number + threads: Node[] = [] + match = false + runs: Run[] = [] + // the sorted ids of the threads, with 0 for a match, once the + // state is done + ids: number[] = [] + + constructor(gen: number) { + this.gen = gen + } + + // no threads, so nothing more can match + get dead() { + return !this.threads.length && !this.match && !this.runs.length + } +} + +// true if the two states hold the same threads +const sameState = (a: State, b: State): boolean => { + if (a.ids.length !== b.ids.length) return false + if (a.runs.length !== b.runs.length) return false + if (a.ids.some((id, i) => id !== b.ids[i])) return false + return a.runs.every(r => + b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)), + ) +} + +/** + * For each node id, the gen of the last state that has the node as + * a thread, and of the last state that walked through it. A state is + * built to the end before the states around it go on, and the nodes + * of a negated sub-pattern are only in its states (other than the + * match node, which is never marked). So one mark for each node is + * enough to know if the state being built has it. The Sims of a + * matcher never run at the same time, so they share one Marks. + */ +export type Marks = { has: Float64Array; seen: Float64Array; gen: number } + +const marks = (size: number): Marks => ({ + has: new Float64Array(size), + seen: new Float64Array(size), + gen: 0, +}) + +class Sim { + // `.` and `..` only match literal dots, even with `dot:true` + dots: boolean + // the string starts with `.`, and `dot:true` is not set + dotStart: boolean + #marks: Marks + + constructor(dots: boolean, dotStart: boolean, marks: Marks) { + this.dots = dots + this.dotStart = dotStart + this.#marks = marks + } + + state() { + return new State(++this.#marks.gen) + } + + // sort the ids of a state, once it has all of its threads + done(state: State) { + state.ids = state.threads.map(n => n.id).sort((a, b) => a - b) + if (state.match) state.ids.unshift(MATCH.id) + return state + } + + // true the first time that the state walks through the node, so + // that loops in the graph stop + #visit(state: State, node: Node) { + const { seen } = this.#marks + if (seen[node.id] === state.gen) return false + seen[node.id] = state.gen + return true + } + + #addThread(state: State, node: Node) { + const { has } = this.#marks + if (has[node.id] === state.gen) return false + has[node.id] = state.gen + state.threads.push(node) + return true + } + + // wildcards only match a leading dot if `dot:true`. In a negated + // sub-pattern, this does not apply, because the negation itself + // can not match a leading dot. + restricted(i: number, top: boolean) { + return top && (this.dots || (this.dotStart && i === 0)) + } + + add(state: State, node: Node, i: number, top: boolean): void { + switch (node.t) { + case 'split': + if (!this.#visit(state, node)) return + for (const o of node.out) this.add(state, o, i, top) + return + case 'neg': + if (!this.#visit(state, node)) return + const sub = this.state() + this.add(sub, node.sub, i, false) + this.done(sub) + return this.addRun( + state, + { t: 'run', neg: node, state: sub }, + i, + top, + ) + case 'star': + // a * can not start a dotfile, even if it matches nothing + if (this.restricted(i, top)) return + if (this.#addThread(state, node)) + this.add(state, node.next, i, top) + return + case 'match': + state.match = true + return + default: + this.#addThread(state, node) + } + } + + addRun(state: State, run: Run, i: number, top: boolean) { + for (const r of state.runs) { + if (r.neg === run.neg && sameState(r.state, run.state)) return + } + state.runs.push(run) + if (!run.state.match) { + this.add(state, run.neg.next, i, top) + } + } + + // the threads after char `c`, at index `i` + step(state: State, c: string, i: number, top: boolean): State { + const next = this.state() + for (const th of state.threads) { + switch (th.t) { + case 'lit': + if (litMatch(th, c)) { + this.add(next, th.next, i + 1, top) + } + break + case 'any': + if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top) + break + case 'class': + if (!this.restricted(i, top) && th.re.test(c)) { + this.add(next, th.next, i + 1, top) + } + break + case 'star': + if (!this.restricted(i, top)) this.add(next, th, i + 1, top) + } + } + if (!this.restricted(i, top)) { + for (const run of state.runs) { + // a sub-pattern with no threads can not match again, so the + // run stays the same + if (run.state.dead) { + this.addRun(next, run, i + 1, top) + continue + } + const sub = this.step(run.state, c, i, false) + this.addRun( + next, + { t: 'run', neg: run.neg, state: sub }, + i + 1, + top, + ) + } + } + return this.done(next) + } +} + +// A canonical key for the threads in a state. States with the same +// key hold the same threads, so they match the same strings. +const stateKey = (state: State): string => { + const ids = state.ids.join() + if (!state.runs.length) return ids + const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`) + return `${ids}|${runs.sort().join('|')}` +} + +// A cached state of the simulation, and the states that each char +// leads to. +type DState = { + state: State + match: boolean + // no threads, so nothing more can match + dead: boolean + // the next state for each ASCII char, by char code, and for the + // other chars + ascii?: (DState | undefined)[] + next: Map +} + +// The cache can hold about this many chars of state keys and +// transitions. When it is full, it is cleared, so that a pattern +// can not use an unbounded amount of memory. +const DFA_BUDGET = 1 << 18 + +// A cache of the states that the simulation reaches, built as the +// matcher is used. Each char of a string is then one Map lookup, +// once the states that it leads to are known. +// +// The dot rules only restrict the first char of a dotfile (strings +// that are only `.` or `..` do not use the cache). So a dotfile +// starts at its own state, which takes its first step with the +// restriction, and every other state takes steps without it. +class Dfa { + #start: Node + #states = new Map() + #size = 0 + #plain?: DState + #dotStart?: DState + #sim: Sim + #dotSim: Sim + + constructor(start: Node, marks: Marks) { + this.#start = start + this.#sim = new Sim(false, false, marks) + this.#dotSim = new Sim(false, true, marks) + } + + #make(state: State): DState { + return { + state, + match: state.match, + dead: state.dead, + next: new Map(), + } + } + + #intern(state: State): DState { + const key = stateKey(state) + const found = this.#states.get(key) + if (found) return found + if (this.#size > DFA_BUDGET) this.#clear() + const d = this.#make(state) + this.#states.set(key, d) + this.#size += key.length + 1 + return d + } + + #clear() { + this.#states.clear() + this.#size = 0 + this.#plain = undefined + this.#dotStart = undefined + } + + start(dotStart: boolean): DState { + if (dotStart) { + if (this.#dotStart) return this.#dotStart + const state = this.#dotSim.state() + this.#dotSim.add(state, this.#start, 0, true) + return (this.#dotStart = this.#make(this.#dotSim.done(state))) + } + if (this.#plain) return this.#plain + const state = this.#sim.state() + this.#sim.add(state, this.#start, 0, true) + return (this.#plain = this.#intern(this.#sim.done(state))) + } + + // the next state, after a miss in `d.ascii` + next(d: DState, c: string): DState { + const code = c.charCodeAt(0) + const found = code < 128 ? undefined : d.next.get(c) + if (found) return found + // the dotfile start is not in the cache, so it is never shared + const n = + d === this.#dotStart ? + this.#intern(this.#dotSim.step(d.state, c, 0, true)) + : this.#intern(this.#sim.step(d.state, c, 1, true)) + if (code < 128) { + if (!d.ascii) { + d.ascii = new Array(128) + this.#size += 128 + } + d.ascii[code] = n + } else { + d.next.set(c, n) + } + this.#size++ + return n + } +} + +/** + * A node in a graph with no splits or negations. Such a graph is a + * chain of nodes that each match one char, or a `*`. + */ +export type LinearNode = Exclude< + Node, + SplitNode | NegNode | { t: 'match' } +> + +// the nodes in order, if the graph is a single chain +const linear = (start: Node): LinearNode[] | undefined => { + const nodes: LinearNode[] = [] + for (let n = start; n.t !== 'match'; n = n.next) { + if (n.t === 'split' || n.t === 'neg') return undefined + nodes.push(n) + } + return nodes +} + +// Match a chain of nodes. Each node other than `*` matches exactly +// one char, so on a failure it is enough to go back to the last `*` +// and let it match one more char. This takes at most +// nodes.length * chars.length steps. +const testLinear = ( + nodes: LinearNode[], + chars: ArrayLike, + start: number, + end: number, +) => { + let ni = 0 + let ci = start + let starNi = -1 + let starCi = 0 + while (ci < end) { + const n = nodes[ni] + if (n?.t === 'star') { + starNi = ni++ + starCi = ci + continue + } + const c = chars[ci]! + if ( + n && + (n.t === 'any' || + (n.t === 'lit' && litMatch(n, c)) || + (n.t === 'class' && n.re.test(c))) + ) { + ni++ + ci++ + continue + } + if (starNi === -1) return false + ni = starNi + 1 + ci = ++starCi + } + while (nodes[ni]?.t === 'star') ni++ + return ni === nodes.length +} + +// The least and most chars that the items can match. These are only +// bounds: a negation can match a string of any length, so it counts +// as 0 to Infinity. +const lengths = (items: Item[]): [min: number, max: number] => { + let min = 0 + let max = 0 + for (const it of items) { + const [lo, hi] = itemLengths(it) + min += lo + max += hi + } + return [min, max] +} + +const itemLengths = (it: Item): [min: number, max: number] => { + if (it.t === 'star') return [0, Infinity] + if (it.t !== 'ext') return [1, 1] + if (it.type === '!') return [0, Infinity] + const alts = it.alts.map(lengths) + const min = Math.min(...alts.map(a => a[0])) + const max = Math.max(...alts.map(a => a[1])) + // a loop of alternatives that only match the empty string is empty + const loop = max === 0 ? 0 : Infinity + return ( + it.type === '@' ? [min, max] + : it.type === '?' ? [0, max] + : it.type === '*' ? [0, loop] + : [min, loop] + ) +} + +// true if the chars from `start` match the literals +const hasAffix = ( + lits: Lit[], + chars: ArrayLike, + start: number, +) => { + for (let j = 0; j < lits.length; j++) { + if (!litMatch(lits[j]!, chars[start + j]!)) return false + } + return true +} + +// a `/`, or half of a surrogate pair +const slashOrSurrogate = /[/\ud800-\udfff]/ +const surrogate = /[\ud800-\udfff]/ + +// a string can be indexed by code point, unless it has surrogate +// pairs +const codePoints = (s: string): ArrayLike => + surrogate.test(s) ? [...s] : s + +const noSlash = (s: string) => { + if (s.includes('/')) { + throw new Error('can only match a single path portion, got: ' + s) + } +} + +export class Matcher { + pattern: string + options: MatcherOptions + #start: Node + // the number of node ids + #size: number + #marks?: Marks + // the Sim for strings that are only `.` or `..` + #dotsSim?: Sim + // the string to compare, if the pattern has no magic. With + // `nocase:true`, the RegExp that folds case is made when it is + // first used. + #literal?: string + #literalFold = false + #literalRe?: RegExp + // the nodes between the prefix and suffix, if the graph is a + // single chain + #linear?: LinearNode[] + // the linear nodes are only `*` and `?`, so the length bounds and + // the prefix and suffix decide the match + #wild = false + // the least and most chars that a match can have + #min = 0 + #max = Infinity + // the literals that a match must start and end with. Each one + // matches exactly one char, and they are distinct items in the + // pattern, so a string that does not have them can not match. + #prefix: Lit[] = [] + #suffix: Lit[] = [] + // the prefix and suffix as strings, if they do not fold case + #prefixStr?: string + #suffixStr?: string + // there is a prefix or suffix to check + #affix = false + #dfa?: Dfa + #form?: Form + + constructor(pattern: string, options: MatcherOptions = {}) { + if (pattern.includes('/')) { + throw new Error( + 'can only match a single path portion, got pattern: ' + pattern, + ) + } + this.pattern = pattern + this.options = options + const { nocase = false, noext = false, normalize: n } = options + this.#form = n === true ? 'NFC' : n || undefined + // a pattern that is only an empty extglob is a literal string, + // except for `!()`, which matches any non-empty string + const literal = /^[?*+@]\(\)$/.test(pattern) + const toks = tokenize( + pattern, + nocase, + noext || literal, + this.#form, + options.rangeMark, + ) + let [items] = build(toks, pair(toks), 0, toks.length, true) + if (this.#form) items = normalize(items!, this.#form) + const [start, size] = compile(items!, nocase) + this.#start = start + this.#size = size + if (items!.every(it => it.t === 'lit')) { + this.#literal = items!.map(it => it.ch).join('') + this.#literalFold = nocase + } else { + const lit = (it: Item): Lit | undefined => + it.t !== 'lit' ? undefined + : nocase ? { ch: it.ch, re: foldRe(it.ch) } + : { ch: it.ch } + for (const it of items!) { + const l = lit(it) + if (!l) break + this.#prefix.push(l) + } + for (let j = items!.length - 1; j >= 0; j--) { + const l = lit(items![j]!) + if (!l) break + this.#suffix.unshift(l) + } + this.#affix = !!(this.#prefix.length || this.#suffix.length) + if (!nocase) { + this.#prefixStr = this.#prefix.map(l => l.ch).join('') + this.#suffixStr = this.#suffix.map(l => l.ch).join('') + } + this.#linear = linear(this.#start)?.slice( + this.#prefix.length, + -this.#suffix.length || undefined, + ) + this.#wild = !!this.#linear?.every( + n => n.t === 'star' || n.t === 'any', + ) + const [min, max] = lengths(items!) + this.#min = min + this.#max = max + } + } + + test(s: string): boolean { + // The `/` check uses the string as given, so with normalization it + // is a separate step. Otherwise, one scan finds both a `/` and the + // surrogate pairs that stop the string being indexed by code point. + if (this.#form) { + noSlash(s) + return this.#test(s.normalize(this.#form)) + } + if (slashOrSurrogate.test(s)) { + noSlash(s) + return this.#test(s, [...s]) + } + return this.#test(s, s) + } + + /** + * The same as {@link Matcher#test}, but the string is not checked + * for `/` chars, so the result for a string that has one is not + * defined. Only use it for a string that is known to be one path + * portion, such as a part of a path that was split on `/`. It can + * be faster, because some patterns do not need to look at each char + * of the string. + */ + testUnchecked(s: string): boolean { + return this.#test(this.#form ? s.normalize(this.#form) : s) + } + + // Test a string that has no `/`. `chars` indexes it by code point. + // If it is not given, it is only found if a step needs it. + #test(s: string, chars?: ArrayLike): boolean { + if (this.#literal !== undefined) { + return this.#literalFold ? + (this.#literalRe ??= newFoldRe(this.#literal)).test(s) + : s === this.#literal + } + // the length check means that the prefix and suffix do not + // overlap. Without the chars, the length in code points is from + // half of the UTF-16 length (if each one is a surrogate pair) to + // all of it, which is often enough to know. + const min = this.#min + const max = this.#max + if (chars === undefined) { + const most = s.length + const least = (most + 1) >> 1 + if (most < min || least > max) return false + if (least < min || most > max) chars = codePoints(s) + } + if ( + chars !== undefined && + (chars.length < min || chars.length > max) + ) { + return false + } + const prefix = this.#prefix.length + if (this.#affix) { + if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) { + if ( + !s.startsWith(this.#prefixStr) || + !s.endsWith(this.#suffixStr) + ) { + return false + } + } else { + chars ??= codePoints(s) + const end = chars.length - this.#suffix.length + if ( + !hasAffix(this.#prefix, chars, 0) || + !hasAffix(this.#suffix, chars, end) + ) { + return false + } + } + } + const dotStart = !this.options.dot && s.startsWith('.') + if (this.#linear) { + // `.` and `..` only match literal dots, even with `dot:true` + if (s === '.' || s === '..') return false + // only a literal can match the leading dot. A `*` can not + // start a dotfile, even if it matches nothing. + if (dotStart && !prefix) return false + if (this.#wild) return true + chars ??= codePoints(s) + const end = chars.length - this.#suffix.length + return testLinear(this.#linear, chars, prefix, end) + } + chars ??= codePoints(s) + if (s === '.' || s === '..') { + this.#marks ??= marks(this.#size) + const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks)) + const start = sim.state() + sim.add(start, this.#start, 0, true) + let state = sim.done(start) + for (let i = 0; i < chars.length; i++) { + state = sim.step(state, chars[i]!, i, true) + } + return state.match + } + this.#marks ??= marks(this.#size) + const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks)) + let d = dfa.start(dotStart) + // read char codes from the string, so that a one-char string is + // only made for a cache miss + const str = chars === s + for (let i = 0; i < chars.length; i++) { + if (d.dead) return false + const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0) + d = d.ascii?.[code] ?? dfa.next(d, chars[i]!) + } + return d.match + } + + /** a readable listing of the state machine */ + toString(): string { + return show(this.#start) + } +} diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/numeric-range.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/numeric-range.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b52e9b492941b83af7c4c050e561df9032e039a --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/numeric-range.ts @@ -0,0 +1,79 @@ +import type { Item } from './index.js' + +// One digit, or a class of digits from a to b. +const digit = (a: number, b: number): Item => + a === b ? + { t: 'lit', ch: String(a) } + : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) } + +const prefix = (d: number, alts: Item[][]) => + alts.map(s => [digit(d, d), ...s]) + +// The digit strings from a to b, which have the same length. +const fixed = (a: string, b: string): Item[][] => { + if (!a) return [[]] + let lo = +a[0]! + let hi = +b[0]! + const ra = a.slice(1) + const rb = b.slice(1) + if (lo === hi) return prefix(lo, fixed(ra, rb)) + const zeros = '0'.repeat(ra.length) + const nines = '9'.repeat(ra.length) + const out: Item[][] = [] + if (ra !== zeros) out.push(...prefix(lo++, fixed(ra, nines))) + const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb)) + if (lo <= hi) { + out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))]) + } + out.push(...last) + return out +} + +// The numbers from a to b, where 0 <= a <= b. If width is set, each +// one has leading zeros to make it that many digits. +const nonneg = (a: number, b: number, width: number): Item[][] => { + if (width) { + return fixed( + String(a).padStart(width, '0'), + String(b).padStart(width, '0'), + ) + } + const out: Item[][] = [] + for (let len = String(a).length; len <= String(b).length; len++) { + const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1)) + const hi = Math.min(b, 10 ** len - 1) + out.push(...fixed(String(lo), String(hi))) + } + return out +} + +/** + * The strings that the bash brace expansion `{lo..hi}` makes, as + * the alternatives of an `@(...)` extglob. Each one is a sequence of + * digits and digit classes, so there are only a few of them, even for + * a large range. + * + * If either end has a leading zero, such as `{01..10}`, each number + * has leading zeros to make it as long as the longer end, counting a + * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`. + * + * Returns undefined if either end is not a safe integer. + */ +export const numericRange = ( + loStr: string, + hiStr: string, +): Item[][] | undefined => { + let lo = Number(loStr) + let hi = Number(hiStr) + if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) return + if (lo > hi) [lo, hi] = [hi, lo] + const padded = /^-?0\d/.test(loStr) || /^-?0\d/.test(hiStr) + const width = padded ? Math.max(loStr.length, hiStr.length) : 0 + const out: Item[][] = [] + if (lo < 0) { + const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1) + out.push(...neg.map(s => [{ t: 'lit', ch: '-' } as Item, ...s])) + } + if (hi >= 0) out.push(...nonneg(Math.max(lo, 0), hi, width)) + return out +} diff --git a/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/parse-class.ts b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/parse-class.ts new file mode 100644 index 0000000000000000000000000000000000000000..945896e1d2794c4f8e405eae23801066a1c3055c --- /dev/null +++ b/mac/patchers/desktop/node_modules/@isaacs/nonrecursive-glob-match/src/parse-class.ts @@ -0,0 +1,158 @@ +// translate the various posix character classes into unicode properties +// this works across all unicode locales + +// { : [, negated] +const posixClasses: { [k: string]: [e: string, n?: boolean] } = { + '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'], + '[:alpha:]': ['\\p{L}\\p{Nl}'], + '[:ascii:]': ['\\x' + '00-\\x' + '7f'], + '[:blank:]': ['\\p{Zs}\\t'], + '[:cntrl:]': ['\\p{Cc}'], + '[:digit:]': ['\\p{Nd}'], + '[:graph:]': ['\\p{Z}\\p{C}', true], + '[:lower:]': ['\\p{Ll}'], + '[:print:]': ['\\p{C}', true], + '[:punct:]': ['\\p{P}\\p{S}'], + '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'], + '[:upper:]': ['\\p{Lu}'], + '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'], + '[:xdigit:]': ['A-Fa-f0-9'], +} + +// only need to escape a few things inside of brace expressions +// escapes: [ \ ] - +const braceEscape = (s: string) => s.replace(/[[\]\\-]/g, '\\$&') + +export type ParseClassResult = [re: RegExp, consumed: number] + +export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD' + +const noMatch = /$./ + +// Takes a glob string at a posix brace expression. Returns a RegExp +// that tests one character, and the number of glob chars consumed. +// If the class is not closed, consumed is 0, and the `[` must be +// treated as a literal character. +// Out of order ranges are removed. If nothing is left, the RegExp +// is `/$./`, and the rest of the glob is consumed, so that the +// whole glob cannot match. +export const parseClass = ( + glob: string, + position: number, + nocase: boolean = false, + form?: Form, +): ParseClassResult => { + // normalize one class member, if it stays one code point + const norm = (c: string) => { + const n = form ? c.normalize(form) : c + return [...n].length === 1 ? n : c + } + const pos = position + /* c8 ignore start */ + if (glob.charAt(pos) !== '[') { + throw new Error('not in a brace expression') + } + /* c8 ignore stop */ + const ranges: string[] = [] + const negs: string[] = [] + + let i = pos + 1 + let sawStart = false + let escaping = false + let negate = false + let endPos = pos + let rangeStart = '' + WHILE: while (i < glob.length) { + const c = String.fromCodePoint(glob.codePointAt(i)!) + if ((c === '!' || c === '^') && i === pos + 1) { + negate = true + i++ + continue + } + + if (c === ']' && sawStart && !escaping) { + endPos = i + 1 + break + } + + sawStart = true + if (c === '\\') { + if (!escaping) { + escaping = true + i++ + continue + } + // escaped \ char, fall through and treat like normal char + } + if (c === '[' && !escaping) { + // either a posix class, a collation equivalent, or just a [ + for (const [cls, [unip, neg]] of Object.entries(posixClasses)) { + if (glob.startsWith(cls, i)) { + // invalid, [a-[] is fine, but not [a-[:alpha]] + if (rangeStart) { + return [noMatch, glob.length - pos] + } + i += cls.length + if (neg) negs.push(unip) + else ranges.push(unip) + continue WHILE + } + } + } + + // now it's just a normal character, effectively + escaping = false + const n = norm(c) + if (rangeStart) { + // throw this range away if it's not valid, but others + // can still match. + if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) { + ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n)) + } else if (n === rangeStart) { + ranges.push(braceEscape(n)) + } + rangeStart = '' + i += c.length + continue + } + + // now might be the start of a range. + // can be either c-d or c-] or c] or c] at this point + if (glob.startsWith('-]', i + c.length)) { + ranges.push(braceEscape(n + '-')) + i += c.length + 1 + continue + } + if (glob.startsWith('-', i + c.length)) { + rangeStart = n + i += c.length + 1 + continue + } + + // not the start of a range, just a single character + ranges.push(braceEscape(n)) + i += c.length + } + + if (endPos < i) { + // didn't see the end of the class, not a valid class, + // but might still be valid as a literal match. + return [noMatch, 0] + } + + // if we got no ranges and no negates, then we have a range that + // cannot possibly match anything, and that poisons the whole glob + if (!ranges.length && !negs.length) { + return [noMatch, glob.length - pos] + } + + const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']' + const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']' + const comb = + '^' + + (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' + : ranges.length ? sranges + : snegs) + + return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos] +} diff --git a/mac/patchers/desktop/node_modules/brace-expansion/README.md b/mac/patchers/desktop/node_modules/brace-expansion/README.md index 073aceb3177ae7babf06970ec4238c00f2527419..eb69a539b559ceb07a9ad9ee44f473c26229e8ae 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/README.md +++ b/mac/patchers/desktop/node_modules/brace-expansion/README.md @@ -75,6 +75,36 @@ const expansions = expand('{a,b}'.repeat(1500), { }) ``` +Three more options bound the work a call does rather than its output. +Past each of them, the part of `str` that is left comes back literally +instead of being expanded, and nothing is thrown. + +- `maxDepth` caps how deeply nested brace sets are followed. This is + limited to `1_000` by default, to prevent stack exhaustion. +- `maxRewrites` caps how many times Bash's `{a},b}` quirk, where a + brace set followed by a comma set still expands, may restart the + parse. This is limited to `1_000` by default. +- `maxSteps` caps the total work: each character the parser scans, + each result it builds and each sequence value it generates is one + step, a zero-padded value is one per character, and each string it + starts expanding, `str` itself or a member of a brace set, costs 16 + more. This is limited to `20_000_000` by default, which takes well + under a second to spend, to prevent CPU exhaustion. Ordinary + patterns need a few hundred steps, and nesting to the full + `maxDepth` about 4 million. If you raise `max` or `maxLength`, + raise this too. + +When `maxSteps` runs out partway, the top-level brace sets before the +point where it ran out stay expanded, so the result can be partly +expanded rather than `[str]`: + +```js +expand('{a,b}' + '{'.repeat(10_000) + 'c,d' + '}'.repeat(10_000)) +// ['a{{{...c,d...}}}', 'b{{{...c,d...}}}'] +``` + +Pass `Infinity` to lift any of these bounds. + Valid expansions are: ```js diff --git a/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.d.ts b/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.d.ts index 1d86e5ec52083b00be390eefad66a03f54c1bffa..1fd22a78d405fd025a5236145de11bd79027e54f 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.d.ts +++ b/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.d.ts @@ -2,11 +2,13 @@ export declare const EXPANSION_MAX = 100000; export declare const EXPANSION_MAX_LENGTH = 4000000; export declare const EXPANSION_MAX_DEPTH = 1000; export declare const EXPANSION_MAX_REWRITES = 1000; +export declare const EXPANSION_MAX_STEPS = 20000000; export type BraceExpansionOptions = { max?: number; maxLength?: number; maxDepth?: number; maxRewrites?: number; + maxSteps?: number; }; export declare function expand(str: string, options?: BraceExpansionOptions): string[]; //# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.d.ts.map b/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.d.ts.map index 581411500b6641af243b84bea472f3acd3b92ae7..84bf6fd655b9137d5ce59758cb1ffba15f475371 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.d.ts.map +++ b/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,aAAa,SAAU,CAAA;AAYpC,eAAO,MAAM,oBAAoB,UAAY,CAAA;AAU7C,eAAO,MAAM,mBAAmB,OAAQ,CAAA;AAUxC,eAAO,MAAM,sBAAsB,OAAQ,CAAA;AAyE3C,MAAM,MAAM,qBAAqB,GAAG;IAClC,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB,CAAA;AAED,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,YA+BtE"} \ No newline at end of file +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,aAAa,SAAU,CAAA;AAYpC,eAAO,MAAM,oBAAoB,UAAY,CAAA;AAU7C,eAAO,MAAM,mBAAmB,OAAQ,CAAA;AAUxC,eAAO,MAAM,sBAAsB,OAAQ,CAAA;AAU3C,eAAO,MAAM,mBAAmB,WAAa,CAAA;AAgL7C,MAAM,MAAM,qBAAqB,GAAG;IAClC,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,CAAA;AAWD,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,YA+BtE"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.js b/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.js index 48cf0d3dabc885249c65909c4912712c834786f5..7397d297b371e68b1fadebb41efbabf7111a89a6 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.js +++ b/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.js @@ -1,13 +1,13 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.EXPANSION_MAX_REWRITES = exports.EXPANSION_MAX_DEPTH = exports.EXPANSION_MAX_LENGTH = exports.EXPANSION_MAX = void 0; +exports.EXPANSION_MAX_STEPS = exports.EXPANSION_MAX_REWRITES = exports.EXPANSION_MAX_DEPTH = exports.EXPANSION_MAX_LENGTH = exports.EXPANSION_MAX = void 0; exports.expand = expand; const balanced_match_1 = require("balanced-match"); -const escSlash = '\0SLASH' + Math.random() + '\0'; -const escOpen = '\0OPEN' + Math.random() + '\0'; -const escClose = '\0CLOSE' + Math.random() + '\0'; -const escComma = '\0COMMA' + Math.random() + '\0'; -const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlash = '\0SLASH' + Math.random().toFixed(16) + '\0'; +const escOpen = '\0OPEN' + Math.random().toFixed(16) + '\0'; +const escClose = '\0CLOSE' + Math.random().toFixed(16) + '\0'; +const escComma = '\0COMMA' + Math.random().toFixed(16) + '\0'; +const escPeriod = '\0PERIOD' + Math.random().toFixed(16) + '\0'; const escSlashPattern = new RegExp(escSlash, 'g'); const escOpenPattern = new RegExp(escOpen, 'g'); const escClosePattern = new RegExp(escClose, 'g'); @@ -48,6 +48,23 @@ exports.EXPANSION_MAX_DEPTH = 1_000; // seconds to produce two results. `EXPANSION_MAX_REWRITES` bounds how many // times the scan may restart. Real `{a},b}` input needs a handful. exports.EXPANSION_MAX_REWRITES = 1_000; +// `EXPANSION_MAX_STEPS` bounds the work one `expand` call does, which `max`, +// `maxLength` and `maxDepth` don't: nested sets are rescanned at every level +// and chained groups each rebuild up to `max` results, so 2KB of input could +// block the event loop for over 30 seconds. Each character scanned, result +// built and sequence value generated is a step, and each `expand_` call costs +// `CALL_STEPS` more. Past the budget, the set being expanded and everything +// after it stay literal. A glob needs a few hundred steps, and nesting all the +// way to `EXPANSION_MAX_DEPTH` about 4M. +exports.EXPANSION_MAX_STEPS = 20_000_000; +// What one `expand_` call costs on top of what it scans and builds. Setting +// one up takes about as long as scanning 16 characters, and a set whose +// results are wrapped to be expanded again makes one call per result, each +// scanning and building next to nothing: 64KB of +// `('{{' + ','.repeat(316) + '}{' + ','.repeat(316) + '}}').repeat(n)` made +// 4M such calls, which spent the budget three times as slowly as anything +// else. +const CALL_STEPS = 16; function numeric(str) { return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); } @@ -73,12 +90,96 @@ function pushAll(target, items) { target.push(items[i]); } } +// `balanced`, run on `masked` (see `maskUnmatchedOpens`), sliced from `str` +// and charged for the characters it walks: up to the group's `}`, or the +// whole string when there is no match or unmatched `{` come first, which +// `unmatched` then flags for masking. Once a call overdraws the budget, it +// and every later one return undefined, so the rest stays literal. +function balancedWithBudget(str, masked, budget) { + if (budget.remaining < 0) { + return undefined; + } + const r = (0, balanced_match_1.range)('{', '}', masked); + const unmatched = r !== undefined && masked.indexOf('{') < r[0]; + budget.remaining -= r && !unmatched ? r[1] + 1 : str.length; + if (!r || budget.remaining < 0) { + return undefined; + } + return { + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + 1, r[1]), + post: str.slice(r[1] + 1), + unmatched, + }; +} +// `masked` with every `{` that has no matching `}` swapped for a `\0`, which +// keeps the length, so a scan of it still lines up with the string it was +// made from. Such a `{` is literal either way, but `balanced` only learns that +// one is unmatched by reading to the end of the string, so with one at the +// head of every group (`'{a,{b,c}'.repeat(n)`) each scan read the rest of the +// input. That was quadratic, and once the step budget charged for it, it ran +// out partway through and left the rest literal. A scan of the masked copy +// stops at the group's `}`. It is one pass, charged as such. +function maskUnmatchedOpens(masked, budget) { + budget.remaining -= masked.length; + const open = []; + for (let i = 0; i < masked.length; i++) { + const c = masked.charCodeAt(i); + if (c === 0x7b) { + open.push(i); + } + else if (c === 0x7d && open.length) { + open.pop(); + } + } + let out = ''; + let last = 0; + for (let i = 0; i < open.length; i++) { + const at = open[i]; + out += masked.slice(last, at) + '\0'; + last = at + 1; + } + return out + masked.slice(last); +} +// Whether `str` has a `,` not followed by another `,`, with a `}` after it on +// the same line - what `/,(?!,).*\}/.test(str)` asks, answered in one pass from +// the end. The regex tries every `,` and backtracks through the rest of its +// line from each, which is quadratic, and the `{a},b}` rewrite asks again on +// every pass. Like a scan, it is charged for the whole string and refused if +// that overdraws the budget. +function commaSetFollows(str, budget) { + budget.remaining -= str.length; + if (budget.remaining < 0) { + return false; + } + // Whether a `}` follows the current position before the line ends + let close = false; + for (let i = str.length - 1; i >= 0; i--) { + const c = str.charCodeAt(i); + if (c === 0x7d) { + close = true; + } + else if (c === 0x0a || c === 0x0d || c === 0x2028 || c === 0x2029) { + // A line terminator, which `.` does not match + close = false; + } + else if (c === 0x2c && close && str.charCodeAt(i + 1) !== 0x2c) { + return true; + } + } + return false; +} /** * Basically just str.split(","), but handling cases * where we have nested braced sections, which should be * treated as individual members, like {a,{b,c},d} + * + * Returns `undefined` if the step budget runs out before the whole set is + * split, since splitting what is left on every comma would tear apart the + * nested sets it still holds. */ -function parseCommaParts(str) { +function parseCommaParts(str, budget) { const parts = []; // Walk the brace groups iteratively. Recursing on `post` once per group let a // chain of them exhaust the stack - the parsing-side counterpart to @@ -88,7 +189,11 @@ function parseCommaParts(str) { // The part the next chunk continues let carry = ''; for (;;) { - const m = (0, balanced_match_1.balanced)('{', '}', str); + // A set's body holds no unmatched `{`, so there is nothing to mask. + const m = balancedWithBudget(str, str, budget); + if (budget.remaining < 0) { + return undefined; + } if (!m) { const tail = str.split(','); tail[0] = carry + tail[0]; @@ -108,11 +213,23 @@ function parseCommaParts(str) { str = post; } } +// An option that is left out, or that is NaN, gets its default. Every +// comparison against NaN is false, so a NaN bound would never be reached: +// `{ maxSteps: NaN }` let 15KB of input block the event loop for 16 seconds, +// and `{ maxDepth: NaN }` overflowed the stack again (CVE-2026-102278). Pass +// `Infinity` to lift a bound. +function bound(value, fallback) { + return value === undefined || isNaN(value) ? fallback : value; +} function expand(str, options = {}) { if (!str) { return []; } - const { max = exports.EXPANSION_MAX, maxLength = exports.EXPANSION_MAX_LENGTH, maxDepth = exports.EXPANSION_MAX_DEPTH, maxRewrites = exports.EXPANSION_MAX_REWRITES, } = options; + const max = bound(options.max, exports.EXPANSION_MAX); + const maxLength = bound(options.maxLength, exports.EXPANSION_MAX_LENGTH); + const maxDepth = bound(options.maxDepth, exports.EXPANSION_MAX_DEPTH); + const maxRewrites = bound(options.maxRewrites, exports.EXPANSION_MAX_REWRITES); + const maxSteps = bound(options.maxSteps, exports.EXPANSION_MAX_STEPS); // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, @@ -122,7 +239,7 @@ function expand(str, options = {}) { if (str.slice(0, 2) === '{}') { str = '\\{\\}' + str.slice(2); } - return expand_(escapeBraces(str), max, maxLength, maxDepth, 0, maxRewrites, true).map(unescapeBraces); + return expand_(escapeBraces(str), max, maxLength, maxDepth, 0, maxRewrites, { remaining: maxSteps }, true).map(unescapeBraces); } function embrace(str) { return '{' + str + '}'; @@ -140,30 +257,41 @@ function gte(i, y) { // number of results at `max` and the total number of characters at `maxLength`. // This is the one place output grows, so bounding it here keeps the single // accumulator - and therefore memory - flat regardless of how many brace groups -// are combined (CVE-2026-14257). -function combine(acc, pre, values, max, maxLength, dropEmpties) { +// are combined (CVE-2026-14257). Each result built is a step, since `max` and +// `maxLength` bound one combination, not how many brace groups are combined. +function combine(acc, pre, values, max, maxLength, dropEmpties, budget) { const out = []; let length = 0; - for (let a = 0; a < acc.length; a++) { - for (let v = 0; v < values.length; v++) { + // Bash drops empty results at the top level, and they don't count against + // `max`, so `max` bounds the number of *kept* results. Only an empty + // `acc[a] + pre` can make one, so for those the empty values are skipped + // without being visited. Visiting them one at a time let a set of empties + // cost `acc.length * values.length` while keeping nothing. + let nonEmpty; + outer: for (let a = 0; a < acc.length; a++) { + const prefix = acc[a] + pre; + let vs = values; + if (dropEmpties && !prefix) { + if (!nonEmpty) + nonEmpty = values.filter(v => v); + vs = nonEmpty; + } + for (let v = 0; v < vs.length; v++) { if (out.length >= max) - return out; - const expansion = acc[a] + pre + values[v]; - // Bash drops empty results at the top level. Skip them before they count - // against `max`, so `max` bounds the number of *kept* results. - if (dropEmpties && !expansion) - continue; + break outer; + const expansion = prefix + vs[v]; if (length + expansion.length > maxLength) - return out; + break outer; out.push(expansion); length += expansion.length; } } + budget.remaining -= out.length; return out; } // The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`) -// sequence body. -function expandSequence(body, isAlphaSequence, max, maxLength) { +// sequence body, or `undefined` if the step budget runs out generating them. +function expandSequence(body, isAlphaSequence, max, maxLength, budget) { const n = body.split(/\.\./); const N = []; // A sequence body always splits into two or three parts, but the compiler @@ -186,8 +314,20 @@ function expandSequence(body, isAlphaSequence, max, maxLength) { test = gte; } const pad = n.some(isPadded); + // A padded value is built a character at a time to `width`, which the input + // sets, so it costs one step per character: 64KB of + // `('{' + '0'.repeat(100) + '..99999}').repeat(n)` took 7 seconds charged + // one step per value. + const cost = pad ? width : 1; let length = 0; for (let i = x; test(i, y) && N.length < max; i += incr) { + // Each value is a step. `max` and `maxLength` bound one sequence, but a + // chain of them still generated up to `max` values each, however few + // combining could keep. + budget.remaining -= cost; + if (budget.remaining < 0) { + return undefined; + } let c; if (isAlphaSequence) { c = String.fromCharCode(i); @@ -217,7 +357,9 @@ function expandSequence(body, isAlphaSequence, max, maxLength) { } return N; } -function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { +function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, budget, isTop) { + // An overdraft here makes the first scan refuse, so `str` stays literal. + budget.remaining -= CALL_STEPS; // Too deeply nested to keep following: treat the rest as literal, the same // way a group that cannot expand is already handled. Truncating rather than // throwing keeps `expand` total, matching `max` and `maxLength`. @@ -240,20 +382,33 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { let rewrites = 0; let dropEmpties = false; let firstGroup = true; + // `str` with its unmatched `{` masked, once a scan has run into them + let masked = str; for (;;) { - const m = (0, balanced_match_1.balanced)('{', '}', str); - // No brace set left: the rest of the string is literal. + const m = balancedWithBudget(str, masked, budget); + // No brace set left, or no step budget left to look for one: the rest of + // the string is literal. if (!m) { - return combine(acc, str, [''], max, maxLength, dropEmpties); + return combine(acc, str, [''], max, maxLength, dropEmpties, budget); + } + if (m.unmatched) { + masked = maskUnmatchedOpens(masked, budget); } // no need to expand pre, since it is guaranteed to be free of brace-sets const pre = m.pre; + // This set and the rest of the string, literal: for a set that cannot + // expand, and for one the step budget runs out on. Once it is overdrawn, + // every set still being expanded, at every level, stays literal like this - + // otherwise each level above would go on combining, and wrapping and + // expanding again, results the budget was too small for. + const literal = () => combine(acc, pre + '{' + m.body + '}' + m.post, [''], max, maxLength, dropEmpties, budget); if (/\$$/.test(pre)) { - acc = combine(acc, pre + '{' + m.body + '}', [''], max, maxLength, dropEmpties && !m.post.length); + acc = combine(acc, pre + '{' + m.body + '}', [''], max, maxLength, dropEmpties && !m.post.length, budget); firstGroup = false; if (!m.post.length) break; str = m.post; + masked = masked.slice(m.end + 1); continue; } const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); @@ -262,14 +417,19 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { const isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} - if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) { + if (rewrites < maxRewrites && commaSetFollows(m.post, budget)) { rewrites++; str = m.pre + '{' + m.body + escClose + m.post; + // Taking a `}` away never gives an unmatched `{` a partner, so what + // is masked stays unmatched. The `{` it closed can be left without + // one, and the next scan masks it. + masked = + masked.slice(0, m.end) + escClose + masked.slice(m.end + 1); isTop = true; continue; } // Nothing here expands, so the whole remaining string is literal. - return combine(acc, pre + '{' + m.body + '}' + m.post, [''], max, maxLength, dropEmpties); + return literal(); } if (firstGroup) { dropEmpties = isTop && !isSequence; @@ -277,20 +437,36 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { } let values; if (isSequence) { - values = expandSequence(m.body, isAlphaSequence, max, maxLength); + values = expandSequence(m.body, isAlphaSequence, max, maxLength, budget); + if (!values) { + return literal(); + } } else { - let n = parseCommaParts(m.body); + let n = parseCommaParts(m.body, budget); + // The step budget ran out partway through the set. + if (!n) { + return literal(); + } if (n.length === 1 && n[0] !== undefined) { // x{{a,b}}y ==> x{a}y x{b}y - n = expand_(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, false).map(embrace); + n = expand_(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, budget, false).map(embrace); + // The step budget ran out expanding the set's only part. + if (budget.remaining < 0) { + return literal(); + } //XXX is this necessary? Can't seem to hit it in tests. /* c8 ignore start */ if (n.length === 1) { - acc = combine(acc, pre + n[0], [''], max, maxLength, dropEmpties && !m.post.length); + const next = combine(acc, pre + n[0], [''], max, maxLength, dropEmpties && !m.post.length, budget); + if (budget.remaining < 0) { + return literal(); + } + acc = next; if (!m.post.length) break; str = m.post; + masked = masked.slice(m.end + 1); continue; } /* c8 ignore stop */ @@ -309,7 +485,11 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { values = []; let valuesLength = 0; outer: for (let j = 0; j < n.length; j++) { - const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false); + const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, budget, false); + // The step budget ran out expanding a member. + if (budget.remaining < 0) { + return literal(); + } for (let k = 0; k < expanded.length; k++) { const v = expanded[k]; if (dropsEmpties && !v) @@ -323,10 +503,16 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { } } } - acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length); + const next = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length, budget); + // The step budget ran out combining the set's values in. + if (budget.remaining < 0) { + return literal(); + } + acc = next; if (!m.post.length) break; str = m.post; + masked = masked.slice(m.end + 1); } return acc; } diff --git a/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.js.map b/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.js.map index 1009b3acd6500940102c2659bfe2cec7593b685e..788ab2ef39f51f2c3b62b2070189f81c49219840 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.js.map +++ b/mac/patchers/desktop/node_modules/brace-expansion/dist/commonjs/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAkIA,wBA+BC;AAjKD,mDAAyC;AAEzC,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AAC/C,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,SAAS,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACnD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;AAC/C,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,gBAAgB,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MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACzC,MAAM,QAAQ,GAAG,OAAO,CACtB,CAAC,CAAC,CAAC,CAAW,EACd,GAAG,EACH,SAAS,EACT,QAAQ,EACR,KAAK,GAAG,CAAC,EACT,WAAW,EACX,KAAK,CACN,CAAA;gBACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;oBACzC,MAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAW,CAAA;oBAC/B,IAAI,YAAY,IAAI,CAAC,CAAC;wBAAE,SAAQ;oBAChC,IACE,MAAM,CAAC,MAAM,IAAI,GAAG;wBACpB,YAAY,GAAG,CAAC,CAAC,MAAM,GAAG,SAAS,EACnC,CAAC;wBACD,MAAM,KAAK,CAAA;oBACb,CAAC;oBACD,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;oBACd,YAAY,IAAI,CAAC,CAAC,MAAM,CAAA;gBAC1B,CAAC;YACH,CAAC;QACH,CAAC;QAED,GAAG,GAAG,OAAO,CACX,GAAG,EACH,GAAG,EACH,MAAM,EACN,GAAG,EACH,SAAS,EACT,WAAW,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAC9B,CAAA;QACD,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM;YAAE,MAAK;QACzB,GAAG,GAAG,CAAC,CAAC,IAAI,CAAA;IACd,CAAC;IAED,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["import { balanced } from 'balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\\\./g\n\nexport const EXPANSION_MAX = 100_000\n\n// `EXPANSION_MAX` caps the *number* of expansions, but not their length. An\n// input like `'{a,b}'.repeat(1500)` stays under that count - its output is\n// truncated to 100k results - while making every result ~1500 characters\n// long. The result set, and the intermediate arrays built while combining\n// brace sets, then grow large enough to exhaust memory and crash the process\n// (CVE-2026-14257). `EXPANSION_MAX_LENGTH` bounds the total number of\n// characters the accumulator may hold at any point, so memory stays flat no\n// matter how many brace groups are chained. The limit sits well above any\n// realistic expansion (100k results hitting `EXPANSION_MAX` measure ~1M\n// characters) so legitimate input is unaffected.\nexport const EXPANSION_MAX_LENGTH = 4_000_000\n\n// `expand_` recurses once per level of brace *nesting* - both when expanding a\n// set's comma members and when re-wrapping a set whose body is a single part.\n// The CVE-2026-14257 fix made the *tail* iterative (recursion on `m.post`, one\n// level per chained group), which left nesting depth unbounded: about 3,100\n// levels of `{{{...a,b...}}}` - only ~6KB of input - exhausted the native stack\n// and crashed the process. `EXPANSION_MAX_DEPTH` bounds how deep the parser\n// will follow nesting. It sits far above any realistic pattern and well below\n// the depth at which the stack runs out.\nexport const EXPANSION_MAX_DEPTH = 1_000\n\n// Bash keeps a quirk where a brace group followed by a comma set still expands\n// (`{a},b}`). The parser implements it by rewriting the string and restarting\n// the scan, absorbing one `}` per pass. `n` trailing braces therefore cost `n`\n// full passes over a string that itself grows by one `escClose` sentinel each\n// time - quadratic in `n`, with a ~26x constant from the sentinel's length.\n// 128KB of `'{a}' + '}'.repeat(n) + ',z}'` blocked the event loop for 27\n// seconds to produce two results. `EXPANSION_MAX_REWRITES` bounds how many\n// times the scan may restart. Real `{a},b}` input needs a handful.\nexport const EXPANSION_MAX_REWRITES = 1_000\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n// Like `target.push(...items)` but doesn't overflow the stack\nfunction pushAll(target: string[], items: string[]) {\n for (let i = 0; i < items.length; i++) {\n target.push(items[i] as string)\n }\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n const parts: string[] = []\n\n // Walk the brace groups iteratively. Recursing on `post` once per group let a\n // chain of them exhaust the stack - the parsing-side counterpart to\n // the `expand_` overflow fixed for CVE-2026-14257, and not something `max` or\n // `maxLength` can bound, since it happens before expansion.\n //\n // The part the next chunk continues\n let carry = ''\n\n for (;;) {\n const m = balanced('{', '}', str)\n\n if (!m) {\n const tail = str.split(',')\n tail[0] = carry + (tail[0] as string)\n pushAll(parts, tail)\n return parts\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n p[0] = carry + (p[0] as string)\n p[p.length - 1] += '{' + body + '}'\n\n if (!post.length) {\n pushAll(parts, p)\n return parts\n }\n\n carry = p.pop() as string\n pushAll(parts, p)\n str = post\n }\n}\n\nexport type BraceExpansionOptions = {\n max?: number\n maxLength?: number\n maxDepth?: number\n maxRewrites?: number\n}\n\nexport function expand(str: string, options: BraceExpansionOptions = {}) {\n if (!str) {\n return []\n }\n\n const {\n max = EXPANSION_MAX,\n maxLength = EXPANSION_MAX_LENGTH,\n maxDepth = EXPANSION_MAX_DEPTH,\n maxRewrites = EXPANSION_MAX_REWRITES,\n } = options\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(\n escapeBraces(str),\n max,\n maxLength,\n maxDepth,\n 0,\n maxRewrites,\n true,\n ).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\n// Build `{ acc[a] + pre + values[v] }` for every combination, capping the\n// number of results at `max` and the total number of characters at `maxLength`.\n// This is the one place output grows, so bounding it here keeps the single\n// accumulator - and therefore memory - flat regardless of how many brace groups\n// are combined (CVE-2026-14257).\nfunction combine(\n acc: string[],\n pre: string,\n values: string[],\n max: number,\n maxLength: number,\n dropEmpties: boolean,\n): string[] {\n const out: string[] = []\n let length = 0\n for (let a = 0; a < acc.length; a++) {\n for (let v = 0; v < values.length; v++) {\n if (out.length >= max) return out\n const expansion = (acc[a] as string) + pre + values[v]\n // Bash drops empty results at the top level. Skip them before they count\n // against `max`, so `max` bounds the number of *kept* results.\n if (dropEmpties && !expansion) continue\n if (length + expansion.length > maxLength) return out\n out.push(expansion)\n length += expansion.length\n }\n }\n return out\n}\n\n// The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)\n// sequence body.\nfunction expandSequence(\n body: string,\n isAlphaSequence: boolean,\n max: number,\n maxLength: number,\n): string[] {\n const n = body.split(/\\.\\./)\n const N: string[] = []\n // A sequence body always splits into two or three parts, but the compiler\n // can't know that.\n /* c8 ignore start */\n if (n[0] === undefined || n[1] === undefined) {\n return N\n }\n /* c8 ignore stop */\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ?\n Math.max(Math.abs(numeric(n[2])), 1)\n : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n let length = 0\n for (let i = x; test(i, y) && N.length < max; i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n if (length + c.length > maxLength) break\n N.push(c)\n length += c.length\n }\n return N\n}\n\nfunction expand_(\n str: string,\n max: number,\n maxLength: number,\n maxDepth: number,\n depth: number,\n maxRewrites: number,\n isTop: boolean,\n): string[] {\n // Too deeply nested to keep following: treat the rest as literal, the same\n // way a group that cannot expand is already handled. Truncating rather than\n // throwing keeps `expand` total, matching `max` and `maxLength`.\n if (depth > maxDepth) {\n return [str]\n }\n\n // Consume the string's top-level brace groups left to right, threading a\n // running set of combined prefixes (`acc`). Expanding the tail iteratively -\n // rather than recursing on `m.post` once per group - keeps the native stack\n // depth constant, so deeply chained input (`'{a,b}'.repeat(3000)`) can no\n // longer overflow the stack, and leaves a single accumulator whose size\n // `maxLength` bounds directly (CVE-2026-14257).\n let acc: string[] = ['']\n\n // Bash drops empty results, but only when the *first* top-level group is a\n // comma set - a sequence like `{a..\\}` may legitimately yield ''. The drop\n // is on the final strings, so it is applied to whichever `combine` produces\n // them (the one with no brace set left in the tail).\n // How many times the `{a},b}` rewrite below has restarted the scan. Each pass\n // re-reads the whole string, so leaving this unbounded is quadratic.\n let rewrites = 0\n let dropEmpties = false\n let firstGroup = true\n\n for (;;) {\n const m = balanced('{', '}', str)\n\n // No brace set left: the rest of the string is literal.\n if (!m) {\n return combine(acc, str, [''], max, maxLength, dropEmpties)\n }\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n\n if (/\\$$/.test(pre)) {\n acc = combine(\n acc,\n pre + '{' + m.body + '}',\n [''],\n max,\n maxLength,\n dropEmpties && !m.post.length,\n )\n firstGroup = false\n if (!m.post.length) break\n str = m.post\n continue\n }\n\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(\n m.body,\n )\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (rewrites < maxRewrites && m.post.match(/,(?!,).*\\}/)) {\n rewrites++\n str = m.pre + '{' + m.body + escClose + m.post\n isTop = true\n continue\n }\n // Nothing here expands, so the whole remaining string is literal.\n return combine(\n acc,\n pre + '{' + m.body + '}' + m.post,\n [''],\n max,\n maxLength,\n dropEmpties,\n )\n }\n\n if (firstGroup) {\n dropEmpties = isTop && !isSequence\n firstGroup = false\n }\n\n let values: string[]\n if (isSequence) {\n values = expandSequence(m.body, isAlphaSequence, max, maxLength)\n } else {\n let n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(\n n[0],\n max,\n maxLength,\n maxDepth,\n depth + 1,\n maxRewrites,\n false,\n ).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n acc = combine(\n acc,\n pre + n[0],\n [''],\n max,\n maxLength,\n dropEmpties && !m.post.length,\n )\n if (!m.post.length) break\n str = m.post\n continue\n }\n /* c8 ignore stop */\n }\n\n // Values that `combine` is going to drop as empty produce no result, so\n // they must not count against `max` - otherwise `{a,,b}` with `max: 2`\n // would stop at `['a', '']` and yield one result instead of two. Skipping\n // them outright keeps `values` bounded while leaving `max` a bound on\n // *kept* results.\n let dropsEmpties = dropEmpties && !m.post.length && !pre\n for (let d = 0; dropsEmpties && d < acc.length; d++) {\n if (acc[d]) {\n dropsEmpties = false\n }\n }\n\n values = []\n let valuesLength = 0\n outer: for (let j = 0; j < n.length; j++) {\n const expanded = expand_(\n n[j] as string,\n max,\n maxLength,\n maxDepth,\n depth + 1,\n maxRewrites,\n false,\n )\n for (let k = 0; k < expanded.length; k++) {\n const v = expanded[k] as string\n if (dropsEmpties && !v) continue\n if (\n values.length >= max ||\n valuesLength + v.length > maxLength\n ) {\n break outer\n }\n values.push(v)\n valuesLength += v.length\n }\n }\n }\n\n acc = combine(\n acc,\n pre,\n values,\n max,\n maxLength,\n dropEmpties && !m.post.length,\n )\n if (!m.post.length) break\n str = m.post\n }\n\n return acc\n}\n"]} \ No newline at end of file +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AA6PA,wBA+BC;AA5RD,mDAAsC;AAEtC,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;AAC7D,MAAM,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;AAC3D,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;AAC7D,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;AAC7D,MAAM,SAAS,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;AAC/D,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;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AA;QACV,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM;YAAE,MAAK;QACzB,GAAG,GAAG,CAAC,CAAC,IAAI,CAAA;QACZ,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAA;IAClC,CAAC;IAED,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["import { range } from 'balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random().toFixed(16) + '\\0'\nconst escOpen = '\\0OPEN' + Math.random().toFixed(16) + '\\0'\nconst escClose = '\\0CLOSE' + Math.random().toFixed(16) + '\\0'\nconst escComma = '\\0COMMA' + Math.random().toFixed(16) + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random().toFixed(16) + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\\\./g\n\nexport const EXPANSION_MAX = 100_000\n\n// `EXPANSION_MAX` caps the *number* of expansions, but not their length. An\n// input like `'{a,b}'.repeat(1500)` stays under that count - its output is\n// truncated to 100k results - while making every result ~1500 characters\n// long. The result set, and the intermediate arrays built while combining\n// brace sets, then grow large enough to exhaust memory and crash the process\n// (CVE-2026-14257). `EXPANSION_MAX_LENGTH` bounds the total number of\n// characters the accumulator may hold at any point, so memory stays flat no\n// matter how many brace groups are chained. The limit sits well above any\n// realistic expansion (100k results hitting `EXPANSION_MAX` measure ~1M\n// characters) so legitimate input is unaffected.\nexport const EXPANSION_MAX_LENGTH = 4_000_000\n\n// `expand_` recurses once per level of brace *nesting* - both when expanding a\n// set's comma members and when re-wrapping a set whose body is a single part.\n// The CVE-2026-14257 fix made the *tail* iterative (recursion on `m.post`, one\n// level per chained group), which left nesting depth unbounded: about 3,100\n// levels of `{{{...a,b...}}}` - only ~6KB of input - exhausted the native stack\n// and crashed the process. `EXPANSION_MAX_DEPTH` bounds how deep the parser\n// will follow nesting. It sits far above any realistic pattern and well below\n// the depth at which the stack runs out.\nexport const EXPANSION_MAX_DEPTH = 1_000\n\n// Bash keeps a quirk where a brace group followed by a comma set still expands\n// (`{a},b}`). The parser implements it by rewriting the string and restarting\n// the scan, absorbing one `}` per pass. `n` trailing braces therefore cost `n`\n// full passes over a string that itself grows by one `escClose` sentinel each\n// time - quadratic in `n`, with a ~26x constant from the sentinel's length.\n// 128KB of `'{a}' + '}'.repeat(n) + ',z}'` blocked the event loop for 27\n// seconds to produce two results. `EXPANSION_MAX_REWRITES` bounds how many\n// times the scan may restart. Real `{a},b}` input needs a handful.\nexport const EXPANSION_MAX_REWRITES = 1_000\n\n// `EXPANSION_MAX_STEPS` bounds the work one `expand` call does, which `max`,\n// `maxLength` and `maxDepth` don't: nested sets are rescanned at every level\n// and chained groups each rebuild up to `max` results, so 2KB of input could\n// block the event loop for over 30 seconds. Each character scanned, result\n// built and sequence value generated is a step, and each `expand_` call costs\n// `CALL_STEPS` more. Past the budget, the set being expanded and everything\n// after it stay literal. A glob needs a few hundred steps, and nesting all the\n// way to `EXPANSION_MAX_DEPTH` about 4M.\nexport const EXPANSION_MAX_STEPS = 20_000_000\n\n// What one `expand_` call costs on top of what it scans and builds. Setting\n// one up takes about as long as scanning 16 characters, and a set whose\n// results are wrapped to be expanded again makes one call per result, each\n// scanning and building next to nothing: 64KB of\n// `('{{' + ','.repeat(316) + '}{' + ','.repeat(316) + '}}').repeat(n)` made\n// 4M such calls, which spent the budget three times as slowly as anything\n// else.\nconst CALL_STEPS = 16\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n// Like `target.push(...items)` but doesn't overflow the stack\nfunction pushAll(target: string[], items: string[]) {\n for (let i = 0; i < items.length; i++) {\n target.push(items[i] as string)\n }\n}\n\n// The step budget for one `expand` call. It is a single counter shared by every\n// level of nesting and every brace group, rather than a per-level limit, so the\n// bound holds for the call as a whole - not `maxDepth * maxSteps`.\ntype Budget = { remaining: number }\n\n// `balanced`, run on `masked` (see `maskUnmatchedOpens`), sliced from `str`\n// and charged for the characters it walks: up to the group's `}`, or the\n// whole string when there is no match or unmatched `{` come first, which\n// `unmatched` then flags for masking. Once a call overdraws the budget, it\n// and every later one return undefined, so the rest stays literal.\nfunction balancedWithBudget(str: string, masked: string, budget: Budget) {\n if (budget.remaining < 0) {\n return undefined\n }\n const r = range('{', '}', masked)\n const unmatched = r !== undefined && masked.indexOf('{') < r[0]\n budget.remaining -= r && !unmatched ? r[1] + 1 : str.length\n if (!r || budget.remaining < 0) {\n return undefined\n }\n return {\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + 1, r[1]),\n post: str.slice(r[1] + 1),\n unmatched,\n }\n}\n\n// `masked` with every `{` that has no matching `}` swapped for a `\\0`, which\n// keeps the length, so a scan of it still lines up with the string it was\n// made from. Such a `{` is literal either way, but `balanced` only learns that\n// one is unmatched by reading to the end of the string, so with one at the\n// head of every group (`'{a,{b,c}'.repeat(n)`) each scan read the rest of the\n// input. That was quadratic, and once the step budget charged for it, it ran\n// out partway through and left the rest literal. A scan of the masked copy\n// stops at the group's `}`. It is one pass, charged as such.\nfunction maskUnmatchedOpens(masked: string, budget: Budget) {\n budget.remaining -= masked.length\n const open: number[] = []\n for (let i = 0; i < masked.length; i++) {\n const c = masked.charCodeAt(i)\n if (c === 0x7b) {\n open.push(i)\n } else if (c === 0x7d && open.length) {\n open.pop()\n }\n }\n let out = ''\n let last = 0\n for (let i = 0; i < open.length; i++) {\n const at = open[i] as number\n out += masked.slice(last, at) + '\\0'\n last = at + 1\n }\n return out + masked.slice(last)\n}\n\n// Whether `str` has a `,` not followed by another `,`, with a `}` after it on\n// the same line - what `/,(?!,).*\\}/.test(str)` asks, answered in one pass from\n// the end. The regex tries every `,` and backtracks through the rest of its\n// line from each, which is quadratic, and the `{a},b}` rewrite asks again on\n// every pass. Like a scan, it is charged for the whole string and refused if\n// that overdraws the budget.\nfunction commaSetFollows(str: string, budget: Budget) {\n budget.remaining -= str.length\n if (budget.remaining < 0) {\n return false\n }\n // Whether a `}` follows the current position before the line ends\n let close = false\n for (let i = str.length - 1; i >= 0; i--) {\n const c = str.charCodeAt(i)\n if (c === 0x7d) {\n close = true\n } else if (c === 0x0a || c === 0x0d || c === 0x2028 || c === 0x2029) {\n // A line terminator, which `.` does not match\n close = false\n } else if (c === 0x2c && close && str.charCodeAt(i + 1) !== 0x2c) {\n return true\n }\n }\n return false\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n *\n * Returns `undefined` if the step budget runs out before the whole set is\n * split, since splitting what is left on every comma would tear apart the\n * nested sets it still holds.\n */\nfunction parseCommaParts(str: string, budget: Budget) {\n const parts: string[] = []\n\n // Walk the brace groups iteratively. Recursing on `post` once per group let a\n // chain of them exhaust the stack - the parsing-side counterpart to\n // the `expand_` overflow fixed for CVE-2026-14257, and not something `max` or\n // `maxLength` can bound, since it happens before expansion.\n //\n // The part the next chunk continues\n let carry = ''\n\n for (;;) {\n // A set's body holds no unmatched `{`, so there is nothing to mask.\n const m = balancedWithBudget(str, str, budget)\n\n if (budget.remaining < 0) {\n return undefined\n }\n\n if (!m) {\n const tail = str.split(',')\n tail[0] = carry + (tail[0] as string)\n pushAll(parts, tail)\n return parts\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n p[0] = carry + (p[0] as string)\n p[p.length - 1] += '{' + body + '}'\n\n if (!post.length) {\n pushAll(parts, p)\n return parts\n }\n\n carry = p.pop() as string\n pushAll(parts, p)\n str = post\n }\n}\n\nexport type BraceExpansionOptions = {\n max?: number\n maxLength?: number\n maxDepth?: number\n maxRewrites?: number\n maxSteps?: number\n}\n\n// An option that is left out, or that is NaN, gets its default. Every\n// comparison against NaN is false, so a NaN bound would never be reached:\n// `{ maxSteps: NaN }` let 15KB of input block the event loop for 16 seconds,\n// and `{ maxDepth: NaN }` overflowed the stack again (CVE-2026-102278). Pass\n// `Infinity` to lift a bound.\nfunction bound(value: number | undefined, fallback: number) {\n return value === undefined || isNaN(value) ? fallback : value\n}\n\nexport function expand(str: string, options: BraceExpansionOptions = {}) {\n if (!str) {\n return []\n }\n\n const max = bound(options.max, EXPANSION_MAX)\n const maxLength = bound(options.maxLength, EXPANSION_MAX_LENGTH)\n const maxDepth = bound(options.maxDepth, EXPANSION_MAX_DEPTH)\n const maxRewrites = bound(options.maxRewrites, EXPANSION_MAX_REWRITES)\n const maxSteps = bound(options.maxSteps, EXPANSION_MAX_STEPS)\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(\n escapeBraces(str),\n max,\n maxLength,\n maxDepth,\n 0,\n maxRewrites,\n { remaining: maxSteps },\n true,\n ).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\n// Build `{ acc[a] + pre + values[v] }` for every combination, capping the\n// number of results at `max` and the total number of characters at `maxLength`.\n// This is the one place output grows, so bounding it here keeps the single\n// accumulator - and therefore memory - flat regardless of how many brace groups\n// are combined (CVE-2026-14257). Each result built is a step, since `max` and\n// `maxLength` bound one combination, not how many brace groups are combined.\nfunction combine(\n acc: string[],\n pre: string,\n values: string[],\n max: number,\n maxLength: number,\n dropEmpties: boolean,\n budget: Budget,\n): string[] {\n const out: string[] = []\n let length = 0\n // Bash drops empty results at the top level, and they don't count against\n // `max`, so `max` bounds the number of *kept* results. Only an empty\n // `acc[a] + pre` can make one, so for those the empty values are skipped\n // without being visited. Visiting them one at a time let a set of empties\n // cost `acc.length * values.length` while keeping nothing.\n let nonEmpty: string[] | undefined\n outer: for (let a = 0; a < acc.length; a++) {\n const prefix = (acc[a] as string) + pre\n let vs = values\n if (dropEmpties && !prefix) {\n if (!nonEmpty) nonEmpty = values.filter(v => v)\n vs = nonEmpty\n }\n for (let v = 0; v < vs.length; v++) {\n if (out.length >= max) break outer\n const expansion = prefix + vs[v]\n if (length + expansion.length > maxLength) break outer\n out.push(expansion)\n length += expansion.length\n }\n }\n budget.remaining -= out.length\n return out\n}\n\n// The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)\n// sequence body, or `undefined` if the step budget runs out generating them.\nfunction expandSequence(\n body: string,\n isAlphaSequence: boolean,\n max: number,\n maxLength: number,\n budget: Budget,\n): string[] | undefined {\n const n = body.split(/\\.\\./)\n const N: string[] = []\n // A sequence body always splits into two or three parts, but the compiler\n // can't know that.\n /* c8 ignore start */\n if (n[0] === undefined || n[1] === undefined) {\n return N\n }\n /* c8 ignore stop */\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ?\n Math.max(Math.abs(numeric(n[2])), 1)\n : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n // A padded value is built a character at a time to `width`, which the input\n // sets, so it costs one step per character: 64KB of\n // `('{' + '0'.repeat(100) + '..99999}').repeat(n)` took 7 seconds charged\n // one step per value.\n const cost = pad ? width : 1\n\n let length = 0\n for (let i = x; test(i, y) && N.length < max; i += incr) {\n // Each value is a step. `max` and `maxLength` bound one sequence, but a\n // chain of them still generated up to `max` values each, however few\n // combining could keep.\n budget.remaining -= cost\n if (budget.remaining < 0) {\n return undefined\n }\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n if (length + c.length > maxLength) break\n N.push(c)\n length += c.length\n }\n return N\n}\n\nfunction expand_(\n str: string,\n max: number,\n maxLength: number,\n maxDepth: number,\n depth: number,\n maxRewrites: number,\n budget: Budget,\n isTop: boolean,\n): string[] {\n // An overdraft here makes the first scan refuse, so `str` stays literal.\n budget.remaining -= CALL_STEPS\n\n // Too deeply nested to keep following: treat the rest as literal, the same\n // way a group that cannot expand is already handled. Truncating rather than\n // throwing keeps `expand` total, matching `max` and `maxLength`.\n if (depth > maxDepth) {\n return [str]\n }\n\n // Consume the string's top-level brace groups left to right, threading a\n // running set of combined prefixes (`acc`). Expanding the tail iteratively -\n // rather than recursing on `m.post` once per group - keeps the native stack\n // depth constant, so deeply chained input (`'{a,b}'.repeat(3000)`) can no\n // longer overflow the stack, and leaves a single accumulator whose size\n // `maxLength` bounds directly (CVE-2026-14257).\n let acc: string[] = ['']\n\n // Bash drops empty results, but only when the *first* top-level group is a\n // comma set - a sequence like `{a..\\}` may legitimately yield ''. The drop\n // is on the final strings, so it is applied to whichever `combine` produces\n // them (the one with no brace set left in the tail).\n // How many times the `{a},b}` rewrite below has restarted the scan. Each pass\n // re-reads the whole string, so leaving this unbounded is quadratic.\n let rewrites = 0\n let dropEmpties = false\n let firstGroup = true\n // `str` with its unmatched `{` masked, once a scan has run into them\n let masked = str\n\n for (;;) {\n const m = balancedWithBudget(str, masked, budget)\n\n // No brace set left, or no step budget left to look for one: the rest of\n // the string is literal.\n if (!m) {\n return combine(acc, str, [''], max, maxLength, dropEmpties, budget)\n }\n if (m.unmatched) {\n masked = maskUnmatchedOpens(masked, budget)\n }\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n\n // This set and the rest of the string, literal: for a set that cannot\n // expand, and for one the step budget runs out on. Once it is overdrawn,\n // every set still being expanded, at every level, stays literal like this -\n // otherwise each level above would go on combining, and wrapping and\n // expanding again, results the budget was too small for.\n const literal = () =>\n combine(\n acc,\n pre + '{' + m.body + '}' + m.post,\n [''],\n max,\n maxLength,\n dropEmpties,\n budget,\n )\n\n if (/\\$$/.test(pre)) {\n acc = combine(\n acc,\n pre + '{' + m.body + '}',\n [''],\n max,\n maxLength,\n dropEmpties && !m.post.length,\n budget,\n )\n firstGroup = false\n if (!m.post.length) break\n str = m.post\n masked = masked.slice(m.end + 1)\n continue\n }\n\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(\n m.body,\n )\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (rewrites < maxRewrites && commaSetFollows(m.post, budget)) {\n rewrites++\n str = m.pre + '{' + m.body + escClose + m.post\n // Taking a `}` away never gives an unmatched `{` a partner, so what\n // is masked stays unmatched. The `{` it closed can be left without\n // one, and the next scan masks it.\n masked =\n masked.slice(0, m.end) + escClose + masked.slice(m.end + 1)\n isTop = true\n continue\n }\n // Nothing here expands, so the whole remaining string is literal.\n return literal()\n }\n\n if (firstGroup) {\n dropEmpties = isTop && !isSequence\n firstGroup = false\n }\n\n let values: string[] | undefined\n if (isSequence) {\n values = expandSequence(\n m.body,\n isAlphaSequence,\n max,\n maxLength,\n budget,\n )\n if (!values) {\n return literal()\n }\n } else {\n let n = parseCommaParts(m.body, budget)\n // The step budget ran out partway through the set.\n if (!n) {\n return literal()\n }\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(\n n[0],\n max,\n maxLength,\n maxDepth,\n depth + 1,\n maxRewrites,\n budget,\n false,\n ).map(embrace)\n // The step budget ran out expanding the set's only part.\n if (budget.remaining < 0) {\n return literal()\n }\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n const next = combine(\n acc,\n pre + n[0],\n [''],\n max,\n maxLength,\n dropEmpties && !m.post.length,\n budget,\n )\n if (budget.remaining < 0) {\n return literal()\n }\n acc = next\n if (!m.post.length) break\n str = m.post\n masked = masked.slice(m.end + 1)\n continue\n }\n /* c8 ignore stop */\n }\n\n // Values that `combine` is going to drop as empty produce no result, so\n // they must not count against `max` - otherwise `{a,,b}` with `max: 2`\n // would stop at `['a', '']` and yield one result instead of two. Skipping\n // them outright keeps `values` bounded while leaving `max` a bound on\n // *kept* results.\n let dropsEmpties = dropEmpties && !m.post.length && !pre\n for (let d = 0; dropsEmpties && d < acc.length; d++) {\n if (acc[d]) {\n dropsEmpties = false\n }\n }\n\n values = []\n let valuesLength = 0\n outer: for (let j = 0; j < n.length; j++) {\n const expanded = expand_(\n n[j] as string,\n max,\n maxLength,\n maxDepth,\n depth + 1,\n maxRewrites,\n budget,\n false,\n )\n // The step budget ran out expanding a member.\n if (budget.remaining < 0) {\n return literal()\n }\n for (let k = 0; k < expanded.length; k++) {\n const v = expanded[k] as string\n if (dropsEmpties && !v) continue\n if (\n values.length >= max ||\n valuesLength + v.length > maxLength\n ) {\n break outer\n }\n values.push(v)\n valuesLength += v.length\n }\n }\n }\n\n const next = combine(\n acc,\n pre,\n values,\n max,\n maxLength,\n dropEmpties && !m.post.length,\n budget,\n )\n // The step budget ran out combining the set's values in.\n if (budget.remaining < 0) {\n return literal()\n }\n acc = next\n if (!m.post.length) break\n str = m.post\n masked = masked.slice(m.end + 1)\n }\n\n return acc\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.d.ts b/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.d.ts index 1d86e5ec52083b00be390eefad66a03f54c1bffa..1fd22a78d405fd025a5236145de11bd79027e54f 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.d.ts +++ b/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.d.ts @@ -2,11 +2,13 @@ export declare const EXPANSION_MAX = 100000; export declare const EXPANSION_MAX_LENGTH = 4000000; export declare const EXPANSION_MAX_DEPTH = 1000; export declare const EXPANSION_MAX_REWRITES = 1000; +export declare const EXPANSION_MAX_STEPS = 20000000; export type BraceExpansionOptions = { max?: number; maxLength?: number; maxDepth?: number; maxRewrites?: number; + maxSteps?: number; }; export declare function expand(str: string, options?: BraceExpansionOptions): string[]; //# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.d.ts.map b/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.d.ts.map index 581411500b6641af243b84bea472f3acd3b92ae7..84bf6fd655b9137d5ce59758cb1ffba15f475371 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.d.ts.map +++ b/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,aAAa,SAAU,CAAA;AAYpC,eAAO,MAAM,oBAAoB,UAAY,CAAA;AAU7C,eAAO,MAAM,mBAAmB,OAAQ,CAAA;AAUxC,eAAO,MAAM,sBAAsB,OAAQ,CAAA;AAyE3C,MAAM,MAAM,qBAAqB,GAAG;IAClC,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB,CAAA;AAED,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,YA+BtE"} \ No newline at end of file +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,aAAa,SAAU,CAAA;AAYpC,eAAO,MAAM,oBAAoB,UAAY,CAAA;AAU7C,eAAO,MAAM,mBAAmB,OAAQ,CAAA;AAUxC,eAAO,MAAM,sBAAsB,OAAQ,CAAA;AAU3C,eAAO,MAAM,mBAAmB,WAAa,CAAA;AAgL7C,MAAM,MAAM,qBAAqB,GAAG;IAClC,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,CAAA;AAWD,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,YA+BtE"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.js b/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.js index 0e0cc962307eb697dc8139ef4c1f86b82380e5cc..ea6488f49745b1c1f6f7ae87bdacef843612db7b 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.js +++ b/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.js @@ -1,9 +1,9 @@ -import { balanced } from 'balanced-match'; -const escSlash = '\0SLASH' + Math.random() + '\0'; -const escOpen = '\0OPEN' + Math.random() + '\0'; -const escClose = '\0CLOSE' + Math.random() + '\0'; -const escComma = '\0COMMA' + Math.random() + '\0'; -const escPeriod = '\0PERIOD' + Math.random() + '\0'; +import { range } from 'balanced-match'; +const escSlash = '\0SLASH' + Math.random().toFixed(16) + '\0'; +const escOpen = '\0OPEN' + Math.random().toFixed(16) + '\0'; +const escClose = '\0CLOSE' + Math.random().toFixed(16) + '\0'; +const escComma = '\0COMMA' + Math.random().toFixed(16) + '\0'; +const escPeriod = '\0PERIOD' + Math.random().toFixed(16) + '\0'; const escSlashPattern = new RegExp(escSlash, 'g'); const escOpenPattern = new RegExp(escOpen, 'g'); const escClosePattern = new RegExp(escClose, 'g'); @@ -44,6 +44,23 @@ export const EXPANSION_MAX_DEPTH = 1_000; // seconds to produce two results. `EXPANSION_MAX_REWRITES` bounds how many // times the scan may restart. Real `{a},b}` input needs a handful. export const EXPANSION_MAX_REWRITES = 1_000; +// `EXPANSION_MAX_STEPS` bounds the work one `expand` call does, which `max`, +// `maxLength` and `maxDepth` don't: nested sets are rescanned at every level +// and chained groups each rebuild up to `max` results, so 2KB of input could +// block the event loop for over 30 seconds. Each character scanned, result +// built and sequence value generated is a step, and each `expand_` call costs +// `CALL_STEPS` more. Past the budget, the set being expanded and everything +// after it stay literal. A glob needs a few hundred steps, and nesting all the +// way to `EXPANSION_MAX_DEPTH` about 4M. +export const EXPANSION_MAX_STEPS = 20_000_000; +// What one `expand_` call costs on top of what it scans and builds. Setting +// one up takes about as long as scanning 16 characters, and a set whose +// results are wrapped to be expanded again makes one call per result, each +// scanning and building next to nothing: 64KB of +// `('{{' + ','.repeat(316) + '}{' + ','.repeat(316) + '}}').repeat(n)` made +// 4M such calls, which spent the budget three times as slowly as anything +// else. +const CALL_STEPS = 16; function numeric(str) { return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); } @@ -69,12 +86,96 @@ function pushAll(target, items) { target.push(items[i]); } } +// `balanced`, run on `masked` (see `maskUnmatchedOpens`), sliced from `str` +// and charged for the characters it walks: up to the group's `}`, or the +// whole string when there is no match or unmatched `{` come first, which +// `unmatched` then flags for masking. Once a call overdraws the budget, it +// and every later one return undefined, so the rest stays literal. +function balancedWithBudget(str, masked, budget) { + if (budget.remaining < 0) { + return undefined; + } + const r = range('{', '}', masked); + const unmatched = r !== undefined && masked.indexOf('{') < r[0]; + budget.remaining -= r && !unmatched ? r[1] + 1 : str.length; + if (!r || budget.remaining < 0) { + return undefined; + } + return { + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + 1, r[1]), + post: str.slice(r[1] + 1), + unmatched, + }; +} +// `masked` with every `{` that has no matching `}` swapped for a `\0`, which +// keeps the length, so a scan of it still lines up with the string it was +// made from. Such a `{` is literal either way, but `balanced` only learns that +// one is unmatched by reading to the end of the string, so with one at the +// head of every group (`'{a,{b,c}'.repeat(n)`) each scan read the rest of the +// input. That was quadratic, and once the step budget charged for it, it ran +// out partway through and left the rest literal. A scan of the masked copy +// stops at the group's `}`. It is one pass, charged as such. +function maskUnmatchedOpens(masked, budget) { + budget.remaining -= masked.length; + const open = []; + for (let i = 0; i < masked.length; i++) { + const c = masked.charCodeAt(i); + if (c === 0x7b) { + open.push(i); + } + else if (c === 0x7d && open.length) { + open.pop(); + } + } + let out = ''; + let last = 0; + for (let i = 0; i < open.length; i++) { + const at = open[i]; + out += masked.slice(last, at) + '\0'; + last = at + 1; + } + return out + masked.slice(last); +} +// Whether `str` has a `,` not followed by another `,`, with a `}` after it on +// the same line - what `/,(?!,).*\}/.test(str)` asks, answered in one pass from +// the end. The regex tries every `,` and backtracks through the rest of its +// line from each, which is quadratic, and the `{a},b}` rewrite asks again on +// every pass. Like a scan, it is charged for the whole string and refused if +// that overdraws the budget. +function commaSetFollows(str, budget) { + budget.remaining -= str.length; + if (budget.remaining < 0) { + return false; + } + // Whether a `}` follows the current position before the line ends + let close = false; + for (let i = str.length - 1; i >= 0; i--) { + const c = str.charCodeAt(i); + if (c === 0x7d) { + close = true; + } + else if (c === 0x0a || c === 0x0d || c === 0x2028 || c === 0x2029) { + // A line terminator, which `.` does not match + close = false; + } + else if (c === 0x2c && close && str.charCodeAt(i + 1) !== 0x2c) { + return true; + } + } + return false; +} /** * Basically just str.split(","), but handling cases * where we have nested braced sections, which should be * treated as individual members, like {a,{b,c},d} + * + * Returns `undefined` if the step budget runs out before the whole set is + * split, since splitting what is left on every comma would tear apart the + * nested sets it still holds. */ -function parseCommaParts(str) { +function parseCommaParts(str, budget) { const parts = []; // Walk the brace groups iteratively. Recursing on `post` once per group let a // chain of them exhaust the stack - the parsing-side counterpart to @@ -84,7 +185,11 @@ function parseCommaParts(str) { // The part the next chunk continues let carry = ''; for (;;) { - const m = balanced('{', '}', str); + // A set's body holds no unmatched `{`, so there is nothing to mask. + const m = balancedWithBudget(str, str, budget); + if (budget.remaining < 0) { + return undefined; + } if (!m) { const tail = str.split(','); tail[0] = carry + tail[0]; @@ -104,11 +209,23 @@ function parseCommaParts(str) { str = post; } } +// An option that is left out, or that is NaN, gets its default. Every +// comparison against NaN is false, so a NaN bound would never be reached: +// `{ maxSteps: NaN }` let 15KB of input block the event loop for 16 seconds, +// and `{ maxDepth: NaN }` overflowed the stack again (CVE-2026-102278). Pass +// `Infinity` to lift a bound. +function bound(value, fallback) { + return value === undefined || isNaN(value) ? fallback : value; +} export function expand(str, options = {}) { if (!str) { return []; } - const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH, maxDepth = EXPANSION_MAX_DEPTH, maxRewrites = EXPANSION_MAX_REWRITES, } = options; + const max = bound(options.max, EXPANSION_MAX); + const maxLength = bound(options.maxLength, EXPANSION_MAX_LENGTH); + const maxDepth = bound(options.maxDepth, EXPANSION_MAX_DEPTH); + const maxRewrites = bound(options.maxRewrites, EXPANSION_MAX_REWRITES); + const maxSteps = bound(options.maxSteps, EXPANSION_MAX_STEPS); // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, @@ -118,7 +235,7 @@ export function expand(str, options = {}) { if (str.slice(0, 2) === '{}') { str = '\\{\\}' + str.slice(2); } - return expand_(escapeBraces(str), max, maxLength, maxDepth, 0, maxRewrites, true).map(unescapeBraces); + return expand_(escapeBraces(str), max, maxLength, maxDepth, 0, maxRewrites, { remaining: maxSteps }, true).map(unescapeBraces); } function embrace(str) { return '{' + str + '}'; @@ -136,30 +253,41 @@ function gte(i, y) { // number of results at `max` and the total number of characters at `maxLength`. // This is the one place output grows, so bounding it here keeps the single // accumulator - and therefore memory - flat regardless of how many brace groups -// are combined (CVE-2026-14257). -function combine(acc, pre, values, max, maxLength, dropEmpties) { +// are combined (CVE-2026-14257). Each result built is a step, since `max` and +// `maxLength` bound one combination, not how many brace groups are combined. +function combine(acc, pre, values, max, maxLength, dropEmpties, budget) { const out = []; let length = 0; - for (let a = 0; a < acc.length; a++) { - for (let v = 0; v < values.length; v++) { + // Bash drops empty results at the top level, and they don't count against + // `max`, so `max` bounds the number of *kept* results. Only an empty + // `acc[a] + pre` can make one, so for those the empty values are skipped + // without being visited. Visiting them one at a time let a set of empties + // cost `acc.length * values.length` while keeping nothing. + let nonEmpty; + outer: for (let a = 0; a < acc.length; a++) { + const prefix = acc[a] + pre; + let vs = values; + if (dropEmpties && !prefix) { + if (!nonEmpty) + nonEmpty = values.filter(v => v); + vs = nonEmpty; + } + for (let v = 0; v < vs.length; v++) { if (out.length >= max) - return out; - const expansion = acc[a] + pre + values[v]; - // Bash drops empty results at the top level. Skip them before they count - // against `max`, so `max` bounds the number of *kept* results. - if (dropEmpties && !expansion) - continue; + break outer; + const expansion = prefix + vs[v]; if (length + expansion.length > maxLength) - return out; + break outer; out.push(expansion); length += expansion.length; } } + budget.remaining -= out.length; return out; } // The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`) -// sequence body. -function expandSequence(body, isAlphaSequence, max, maxLength) { +// sequence body, or `undefined` if the step budget runs out generating them. +function expandSequence(body, isAlphaSequence, max, maxLength, budget) { const n = body.split(/\.\./); const N = []; // A sequence body always splits into two or three parts, but the compiler @@ -182,8 +310,20 @@ function expandSequence(body, isAlphaSequence, max, maxLength) { test = gte; } const pad = n.some(isPadded); + // A padded value is built a character at a time to `width`, which the input + // sets, so it costs one step per character: 64KB of + // `('{' + '0'.repeat(100) + '..99999}').repeat(n)` took 7 seconds charged + // one step per value. + const cost = pad ? width : 1; let length = 0; for (let i = x; test(i, y) && N.length < max; i += incr) { + // Each value is a step. `max` and `maxLength` bound one sequence, but a + // chain of them still generated up to `max` values each, however few + // combining could keep. + budget.remaining -= cost; + if (budget.remaining < 0) { + return undefined; + } let c; if (isAlphaSequence) { c = String.fromCharCode(i); @@ -213,7 +353,9 @@ function expandSequence(body, isAlphaSequence, max, maxLength) { } return N; } -function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { +function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, budget, isTop) { + // An overdraft here makes the first scan refuse, so `str` stays literal. + budget.remaining -= CALL_STEPS; // Too deeply nested to keep following: treat the rest as literal, the same // way a group that cannot expand is already handled. Truncating rather than // throwing keeps `expand` total, matching `max` and `maxLength`. @@ -236,20 +378,33 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { let rewrites = 0; let dropEmpties = false; let firstGroup = true; + // `str` with its unmatched `{` masked, once a scan has run into them + let masked = str; for (;;) { - const m = balanced('{', '}', str); - // No brace set left: the rest of the string is literal. + const m = balancedWithBudget(str, masked, budget); + // No brace set left, or no step budget left to look for one: the rest of + // the string is literal. if (!m) { - return combine(acc, str, [''], max, maxLength, dropEmpties); + return combine(acc, str, [''], max, maxLength, dropEmpties, budget); + } + if (m.unmatched) { + masked = maskUnmatchedOpens(masked, budget); } // no need to expand pre, since it is guaranteed to be free of brace-sets const pre = m.pre; + // This set and the rest of the string, literal: for a set that cannot + // expand, and for one the step budget runs out on. Once it is overdrawn, + // every set still being expanded, at every level, stays literal like this - + // otherwise each level above would go on combining, and wrapping and + // expanding again, results the budget was too small for. + const literal = () => combine(acc, pre + '{' + m.body + '}' + m.post, [''], max, maxLength, dropEmpties, budget); if (/\$$/.test(pre)) { - acc = combine(acc, pre + '{' + m.body + '}', [''], max, maxLength, dropEmpties && !m.post.length); + acc = combine(acc, pre + '{' + m.body + '}', [''], max, maxLength, dropEmpties && !m.post.length, budget); firstGroup = false; if (!m.post.length) break; str = m.post; + masked = masked.slice(m.end + 1); continue; } const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); @@ -258,14 +413,19 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { const isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} - if (rewrites < maxRewrites && m.post.match(/,(?!,).*\}/)) { + if (rewrites < maxRewrites && commaSetFollows(m.post, budget)) { rewrites++; str = m.pre + '{' + m.body + escClose + m.post; + // Taking a `}` away never gives an unmatched `{` a partner, so what + // is masked stays unmatched. The `{` it closed can be left without + // one, and the next scan masks it. + masked = + masked.slice(0, m.end) + escClose + masked.slice(m.end + 1); isTop = true; continue; } // Nothing here expands, so the whole remaining string is literal. - return combine(acc, pre + '{' + m.body + '}' + m.post, [''], max, maxLength, dropEmpties); + return literal(); } if (firstGroup) { dropEmpties = isTop && !isSequence; @@ -273,20 +433,36 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { } let values; if (isSequence) { - values = expandSequence(m.body, isAlphaSequence, max, maxLength); + values = expandSequence(m.body, isAlphaSequence, max, maxLength, budget); + if (!values) { + return literal(); + } } else { - let n = parseCommaParts(m.body); + let n = parseCommaParts(m.body, budget); + // The step budget ran out partway through the set. + if (!n) { + return literal(); + } if (n.length === 1 && n[0] !== undefined) { // x{{a,b}}y ==> x{a}y x{b}y - n = expand_(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, false).map(embrace); + n = expand_(n[0], max, maxLength, maxDepth, depth + 1, maxRewrites, budget, false).map(embrace); + // The step budget ran out expanding the set's only part. + if (budget.remaining < 0) { + return literal(); + } //XXX is this necessary? Can't seem to hit it in tests. /* c8 ignore start */ if (n.length === 1) { - acc = combine(acc, pre + n[0], [''], max, maxLength, dropEmpties && !m.post.length); + const next = combine(acc, pre + n[0], [''], max, maxLength, dropEmpties && !m.post.length, budget); + if (budget.remaining < 0) { + return literal(); + } + acc = next; if (!m.post.length) break; str = m.post; + masked = masked.slice(m.end + 1); continue; } /* c8 ignore stop */ @@ -305,7 +481,11 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { values = []; let valuesLength = 0; outer: for (let j = 0; j < n.length; j++) { - const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, false); + const expanded = expand_(n[j], max, maxLength, maxDepth, depth + 1, maxRewrites, budget, false); + // The step budget ran out expanding a member. + if (budget.remaining < 0) { + return literal(); + } for (let k = 0; k < expanded.length; k++) { const v = expanded[k]; if (dropsEmpties && !v) @@ -319,10 +499,16 @@ function expand_(str, max, maxLength, maxDepth, depth, maxRewrites, isTop) { } } } - acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length); + const next = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length, budget); + // The step budget ran out combining the set's values in. + if (budget.remaining < 0) { + return literal(); + } + acc = next; if (!m.post.length) break; str = m.post; + masked = masked.slice(m.end + 1); } return acc; } diff --git a/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.js.map b/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.js.map index 28919351779d229b2139720df08350f5a4e9f198..4aeabe098889d1fe75097417f774f18282cc9d58 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.js.map +++ b/mac/patchers/desktop/node_modules/brace-expansion/dist/esm/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEzC,MAAM,QAAQ,GAAG,SAAS,GAAG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,CAAA;oBACb,CAAC;oBACD,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;oBACd,YAAY,IAAI,CAAC,CAAC,MAAM,CAAA;gBAC1B,CAAC;YACH,CAAC;QACH,CAAC;QAED,GAAG,GAAG,OAAO,CACX,GAAG,EACH,GAAG,EACH,MAAM,EACN,GAAG,EACH,SAAS,EACT,WAAW,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAC9B,CAAA;QACD,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM;YAAE,MAAK;QACzB,GAAG,GAAG,CAAC,CAAC,IAAI,CAAA;IACd,CAAC;IAED,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["import { balanced } from 'balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\\\./g\n\nexport const EXPANSION_MAX = 100_000\n\n// `EXPANSION_MAX` caps the *number* of expansions, but not their length. An\n// input like `'{a,b}'.repeat(1500)` stays under that count - its output is\n// truncated to 100k results - while making every result ~1500 characters\n// long. The result set, and the intermediate arrays built while combining\n// brace sets, then grow large enough to exhaust memory and crash the process\n// (CVE-2026-14257). `EXPANSION_MAX_LENGTH` bounds the total number of\n// characters the accumulator may hold at any point, so memory stays flat no\n// matter how many brace groups are chained. The limit sits well above any\n// realistic expansion (100k results hitting `EXPANSION_MAX` measure ~1M\n// characters) so legitimate input is unaffected.\nexport const EXPANSION_MAX_LENGTH = 4_000_000\n\n// `expand_` recurses once per level of brace *nesting* - both when expanding a\n// set's comma members and when re-wrapping a set whose body is a single part.\n// The CVE-2026-14257 fix made the *tail* iterative (recursion on `m.post`, one\n// level per chained group), which left nesting depth unbounded: about 3,100\n// levels of `{{{...a,b...}}}` - only ~6KB of input - exhausted the native stack\n// and crashed the process. `EXPANSION_MAX_DEPTH` bounds how deep the parser\n// will follow nesting. It sits far above any realistic pattern and well below\n// the depth at which the stack runs out.\nexport const EXPANSION_MAX_DEPTH = 1_000\n\n// Bash keeps a quirk where a brace group followed by a comma set still expands\n// (`{a},b}`). The parser implements it by rewriting the string and restarting\n// the scan, absorbing one `}` per pass. `n` trailing braces therefore cost `n`\n// full passes over a string that itself grows by one `escClose` sentinel each\n// time - quadratic in `n`, with a ~26x constant from the sentinel's length.\n// 128KB of `'{a}' + '}'.repeat(n) + ',z}'` blocked the event loop for 27\n// seconds to produce two results. `EXPANSION_MAX_REWRITES` bounds how many\n// times the scan may restart. Real `{a},b}` input needs a handful.\nexport const EXPANSION_MAX_REWRITES = 1_000\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n// Like `target.push(...items)` but doesn't overflow the stack\nfunction pushAll(target: string[], items: string[]) {\n for (let i = 0; i < items.length; i++) {\n target.push(items[i] as string)\n }\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n const parts: string[] = []\n\n // Walk the brace groups iteratively. Recursing on `post` once per group let a\n // chain of them exhaust the stack - the parsing-side counterpart to\n // the `expand_` overflow fixed for CVE-2026-14257, and not something `max` or\n // `maxLength` can bound, since it happens before expansion.\n //\n // The part the next chunk continues\n let carry = ''\n\n for (;;) {\n const m = balanced('{', '}', str)\n\n if (!m) {\n const tail = str.split(',')\n tail[0] = carry + (tail[0] as string)\n pushAll(parts, tail)\n return parts\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n p[0] = carry + (p[0] as string)\n p[p.length - 1] += '{' + body + '}'\n\n if (!post.length) {\n pushAll(parts, p)\n return parts\n }\n\n carry = p.pop() as string\n pushAll(parts, p)\n str = post\n }\n}\n\nexport type BraceExpansionOptions = {\n max?: number\n maxLength?: number\n maxDepth?: number\n maxRewrites?: number\n}\n\nexport function expand(str: string, options: BraceExpansionOptions = {}) {\n if (!str) {\n return []\n }\n\n const {\n max = EXPANSION_MAX,\n maxLength = EXPANSION_MAX_LENGTH,\n maxDepth = EXPANSION_MAX_DEPTH,\n maxRewrites = EXPANSION_MAX_REWRITES,\n } = options\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(\n escapeBraces(str),\n max,\n maxLength,\n maxDepth,\n 0,\n maxRewrites,\n true,\n ).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\n// Build `{ acc[a] + pre + values[v] }` for every combination, capping the\n// number of results at `max` and the total number of characters at `maxLength`.\n// This is the one place output grows, so bounding it here keeps the single\n// accumulator - and therefore memory - flat regardless of how many brace groups\n// are combined (CVE-2026-14257).\nfunction combine(\n acc: string[],\n pre: string,\n values: string[],\n max: number,\n maxLength: number,\n dropEmpties: boolean,\n): string[] {\n const out: string[] = []\n let length = 0\n for (let a = 0; a < acc.length; a++) {\n for (let v = 0; v < values.length; v++) {\n if (out.length >= max) return out\n const expansion = (acc[a] as string) + pre + values[v]\n // Bash drops empty results at the top level. Skip them before they count\n // against `max`, so `max` bounds the number of *kept* results.\n if (dropEmpties && !expansion) continue\n if (length + expansion.length > maxLength) return out\n out.push(expansion)\n length += expansion.length\n }\n }\n return out\n}\n\n// The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)\n// sequence body.\nfunction expandSequence(\n body: string,\n isAlphaSequence: boolean,\n max: number,\n maxLength: number,\n): string[] {\n const n = body.split(/\\.\\./)\n const N: string[] = []\n // A sequence body always splits into two or three parts, but the compiler\n // can't know that.\n /* c8 ignore start */\n if (n[0] === undefined || n[1] === undefined) {\n return N\n }\n /* c8 ignore stop */\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ?\n Math.max(Math.abs(numeric(n[2])), 1)\n : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n let length = 0\n for (let i = x; test(i, y) && N.length < max; i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n if (length + c.length > maxLength) break\n N.push(c)\n length += c.length\n }\n return N\n}\n\nfunction expand_(\n str: string,\n max: number,\n maxLength: number,\n maxDepth: number,\n depth: number,\n maxRewrites: number,\n isTop: boolean,\n): string[] {\n // Too deeply nested to keep following: treat the rest as literal, the same\n // way a group that cannot expand is already handled. Truncating rather than\n // throwing keeps `expand` total, matching `max` and `maxLength`.\n if (depth > maxDepth) {\n return [str]\n }\n\n // Consume the string's top-level brace groups left to right, threading a\n // running set of combined prefixes (`acc`). Expanding the tail iteratively -\n // rather than recursing on `m.post` once per group - keeps the native stack\n // depth constant, so deeply chained input (`'{a,b}'.repeat(3000)`) can no\n // longer overflow the stack, and leaves a single accumulator whose size\n // `maxLength` bounds directly (CVE-2026-14257).\n let acc: string[] = ['']\n\n // Bash drops empty results, but only when the *first* top-level group is a\n // comma set - a sequence like `{a..\\}` may legitimately yield ''. The drop\n // is on the final strings, so it is applied to whichever `combine` produces\n // them (the one with no brace set left in the tail).\n // How many times the `{a},b}` rewrite below has restarted the scan. Each pass\n // re-reads the whole string, so leaving this unbounded is quadratic.\n let rewrites = 0\n let dropEmpties = false\n let firstGroup = true\n\n for (;;) {\n const m = balanced('{', '}', str)\n\n // No brace set left: the rest of the string is literal.\n if (!m) {\n return combine(acc, str, [''], max, maxLength, dropEmpties)\n }\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n\n if (/\\$$/.test(pre)) {\n acc = combine(\n acc,\n pre + '{' + m.body + '}',\n [''],\n max,\n maxLength,\n dropEmpties && !m.post.length,\n )\n firstGroup = false\n if (!m.post.length) break\n str = m.post\n continue\n }\n\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(\n m.body,\n )\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (rewrites < maxRewrites && m.post.match(/,(?!,).*\\}/)) {\n rewrites++\n str = m.pre + '{' + m.body + escClose + m.post\n isTop = true\n continue\n }\n // Nothing here expands, so the whole remaining string is literal.\n return combine(\n acc,\n pre + '{' + m.body + '}' + m.post,\n [''],\n max,\n maxLength,\n dropEmpties,\n )\n }\n\n if (firstGroup) {\n dropEmpties = isTop && !isSequence\n firstGroup = false\n }\n\n let values: string[]\n if (isSequence) {\n values = expandSequence(m.body, isAlphaSequence, max, maxLength)\n } else {\n let n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(\n n[0],\n max,\n maxLength,\n maxDepth,\n depth + 1,\n maxRewrites,\n false,\n ).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n acc = combine(\n acc,\n pre + n[0],\n [''],\n max,\n maxLength,\n dropEmpties && !m.post.length,\n )\n if (!m.post.length) break\n str = m.post\n continue\n }\n /* c8 ignore stop */\n }\n\n // Values that `combine` is going to drop as empty produce no result, so\n // they must not count against `max` - otherwise `{a,,b}` with `max: 2`\n // would stop at `['a', '']` and yield one result instead of two. Skipping\n // them outright keeps `values` bounded while leaving `max` a bound on\n // *kept* results.\n let dropsEmpties = dropEmpties && !m.post.length && !pre\n for (let d = 0; dropsEmpties && d < acc.length; d++) {\n if (acc[d]) {\n dropsEmpties = false\n }\n }\n\n values = []\n let valuesLength = 0\n outer: for (let j = 0; j < n.length; j++) {\n const expanded = expand_(\n n[j] as string,\n max,\n maxLength,\n maxDepth,\n depth + 1,\n maxRewrites,\n false,\n )\n for (let k = 0; k < expanded.length; k++) {\n const v = expanded[k] as string\n if (dropsEmpties && !v) continue\n if (\n values.length >= max ||\n valuesLength + v.length > maxLength\n ) {\n break outer\n }\n values.push(v)\n valuesLength += v.length\n }\n }\n }\n\n acc = combine(\n acc,\n pre,\n values,\n max,\n maxLength,\n dropEmpties && !m.post.length,\n )\n if (!m.post.length) break\n str = m.post\n }\n\n return acc\n}\n"]} \ No newline at end of file +{"version":3,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,CAAC;gBACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;oBACzC,MAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAW,CAAA;oBAC/B,IAAI,YAAY,IAAI,CAAC,CAAC;wBAAE,SAAQ;oBAChC,IACE,MAAM,CAAC,MAAM,IAAI,GAAG;wBACpB,YAAY,GAAG,CAAC,CAAC,MAAM,GAAG,SAAS,EACnC,CAAC;wBACD,MAAM,KAAK,CAAA;oBACb,CAAC;oBACD,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;oBACd,YAAY,IAAI,CAAC,CAAC,MAAM,CAAA;gBAC1B,CAAC;YACH,CAAC;QACH,CAAC;QAED,MAAM,IAAI,GAAG,OAAO,CAClB,GAAG,EACH,GAAG,EACH,MAAM,EACN,GAAG,EACH,SAAS,EACT,WAAW,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAC7B,MAAM,CACP,CAAA;QACD,yDAAyD;QACzD,IAAI,MAAM,CAAC,SAAS,GAAG,CAAC,EAAE,CAAC;YACzB,OAAO,OAAO,EAAE,CAAA;QAClB,CAAC;QACD,GAAG,GAAG,IAAI,CAAA;QACV,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM;YAAE,MAAK;QACzB,GAAG,GAAG,CAAC,CAAC,IAAI,CAAA;QACZ,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAA;IAClC,CAAC;IAED,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["import { range } from 'balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random().toFixed(16) + '\\0'\nconst escOpen = '\\0OPEN' + Math.random().toFixed(16) + '\\0'\nconst escClose = '\\0CLOSE' + Math.random().toFixed(16) + '\\0'\nconst escComma = '\\0COMMA' + Math.random().toFixed(16) + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random().toFixed(16) + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\\\./g\n\nexport const EXPANSION_MAX = 100_000\n\n// `EXPANSION_MAX` caps the *number* of expansions, but not their length. An\n// input like `'{a,b}'.repeat(1500)` stays under that count - its output is\n// truncated to 100k results - while making every result ~1500 characters\n// long. The result set, and the intermediate arrays built while combining\n// brace sets, then grow large enough to exhaust memory and crash the process\n// (CVE-2026-14257). `EXPANSION_MAX_LENGTH` bounds the total number of\n// characters the accumulator may hold at any point, so memory stays flat no\n// matter how many brace groups are chained. The limit sits well above any\n// realistic expansion (100k results hitting `EXPANSION_MAX` measure ~1M\n// characters) so legitimate input is unaffected.\nexport const EXPANSION_MAX_LENGTH = 4_000_000\n\n// `expand_` recurses once per level of brace *nesting* - both when expanding a\n// set's comma members and when re-wrapping a set whose body is a single part.\n// The CVE-2026-14257 fix made the *tail* iterative (recursion on `m.post`, one\n// level per chained group), which left nesting depth unbounded: about 3,100\n// levels of `{{{...a,b...}}}` - only ~6KB of input - exhausted the native stack\n// and crashed the process. `EXPANSION_MAX_DEPTH` bounds how deep the parser\n// will follow nesting. It sits far above any realistic pattern and well below\n// the depth at which the stack runs out.\nexport const EXPANSION_MAX_DEPTH = 1_000\n\n// Bash keeps a quirk where a brace group followed by a comma set still expands\n// (`{a},b}`). The parser implements it by rewriting the string and restarting\n// the scan, absorbing one `}` per pass. `n` trailing braces therefore cost `n`\n// full passes over a string that itself grows by one `escClose` sentinel each\n// time - quadratic in `n`, with a ~26x constant from the sentinel's length.\n// 128KB of `'{a}' + '}'.repeat(n) + ',z}'` blocked the event loop for 27\n// seconds to produce two results. `EXPANSION_MAX_REWRITES` bounds how many\n// times the scan may restart. Real `{a},b}` input needs a handful.\nexport const EXPANSION_MAX_REWRITES = 1_000\n\n// `EXPANSION_MAX_STEPS` bounds the work one `expand` call does, which `max`,\n// `maxLength` and `maxDepth` don't: nested sets are rescanned at every level\n// and chained groups each rebuild up to `max` results, so 2KB of input could\n// block the event loop for over 30 seconds. Each character scanned, result\n// built and sequence value generated is a step, and each `expand_` call costs\n// `CALL_STEPS` more. Past the budget, the set being expanded and everything\n// after it stay literal. A glob needs a few hundred steps, and nesting all the\n// way to `EXPANSION_MAX_DEPTH` about 4M.\nexport const EXPANSION_MAX_STEPS = 20_000_000\n\n// What one `expand_` call costs on top of what it scans and builds. Setting\n// one up takes about as long as scanning 16 characters, and a set whose\n// results are wrapped to be expanded again makes one call per result, each\n// scanning and building next to nothing: 64KB of\n// `('{{' + ','.repeat(316) + '}{' + ','.repeat(316) + '}}').repeat(n)` made\n// 4M such calls, which spent the budget three times as slowly as anything\n// else.\nconst CALL_STEPS = 16\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n// Like `target.push(...items)` but doesn't overflow the stack\nfunction pushAll(target: string[], items: string[]) {\n for (let i = 0; i < items.length; i++) {\n target.push(items[i] as string)\n }\n}\n\n// The step budget for one `expand` call. It is a single counter shared by every\n// level of nesting and every brace group, rather than a per-level limit, so the\n// bound holds for the call as a whole - not `maxDepth * maxSteps`.\ntype Budget = { remaining: number }\n\n// `balanced`, run on `masked` (see `maskUnmatchedOpens`), sliced from `str`\n// and charged for the characters it walks: up to the group's `}`, or the\n// whole string when there is no match or unmatched `{` come first, which\n// `unmatched` then flags for masking. Once a call overdraws the budget, it\n// and every later one return undefined, so the rest stays literal.\nfunction balancedWithBudget(str: string, masked: string, budget: Budget) {\n if (budget.remaining < 0) {\n return undefined\n }\n const r = range('{', '}', masked)\n const unmatched = r !== undefined && masked.indexOf('{') < r[0]\n budget.remaining -= r && !unmatched ? r[1] + 1 : str.length\n if (!r || budget.remaining < 0) {\n return undefined\n }\n return {\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + 1, r[1]),\n post: str.slice(r[1] + 1),\n unmatched,\n }\n}\n\n// `masked` with every `{` that has no matching `}` swapped for a `\\0`, which\n// keeps the length, so a scan of it still lines up with the string it was\n// made from. Such a `{` is literal either way, but `balanced` only learns that\n// one is unmatched by reading to the end of the string, so with one at the\n// head of every group (`'{a,{b,c}'.repeat(n)`) each scan read the rest of the\n// input. That was quadratic, and once the step budget charged for it, it ran\n// out partway through and left the rest literal. A scan of the masked copy\n// stops at the group's `}`. It is one pass, charged as such.\nfunction maskUnmatchedOpens(masked: string, budget: Budget) {\n budget.remaining -= masked.length\n const open: number[] = []\n for (let i = 0; i < masked.length; i++) {\n const c = masked.charCodeAt(i)\n if (c === 0x7b) {\n open.push(i)\n } else if (c === 0x7d && open.length) {\n open.pop()\n }\n }\n let out = ''\n let last = 0\n for (let i = 0; i < open.length; i++) {\n const at = open[i] as number\n out += masked.slice(last, at) + '\\0'\n last = at + 1\n }\n return out + masked.slice(last)\n}\n\n// Whether `str` has a `,` not followed by another `,`, with a `}` after it on\n// the same line - what `/,(?!,).*\\}/.test(str)` asks, answered in one pass from\n// the end. The regex tries every `,` and backtracks through the rest of its\n// line from each, which is quadratic, and the `{a},b}` rewrite asks again on\n// every pass. Like a scan, it is charged for the whole string and refused if\n// that overdraws the budget.\nfunction commaSetFollows(str: string, budget: Budget) {\n budget.remaining -= str.length\n if (budget.remaining < 0) {\n return false\n }\n // Whether a `}` follows the current position before the line ends\n let close = false\n for (let i = str.length - 1; i >= 0; i--) {\n const c = str.charCodeAt(i)\n if (c === 0x7d) {\n close = true\n } else if (c === 0x0a || c === 0x0d || c === 0x2028 || c === 0x2029) {\n // A line terminator, which `.` does not match\n close = false\n } else if (c === 0x2c && close && str.charCodeAt(i + 1) !== 0x2c) {\n return true\n }\n }\n return false\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n *\n * Returns `undefined` if the step budget runs out before the whole set is\n * split, since splitting what is left on every comma would tear apart the\n * nested sets it still holds.\n */\nfunction parseCommaParts(str: string, budget: Budget) {\n const parts: string[] = []\n\n // Walk the brace groups iteratively. Recursing on `post` once per group let a\n // chain of them exhaust the stack - the parsing-side counterpart to\n // the `expand_` overflow fixed for CVE-2026-14257, and not something `max` or\n // `maxLength` can bound, since it happens before expansion.\n //\n // The part the next chunk continues\n let carry = ''\n\n for (;;) {\n // A set's body holds no unmatched `{`, so there is nothing to mask.\n const m = balancedWithBudget(str, str, budget)\n\n if (budget.remaining < 0) {\n return undefined\n }\n\n if (!m) {\n const tail = str.split(',')\n tail[0] = carry + (tail[0] as string)\n pushAll(parts, tail)\n return parts\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n p[0] = carry + (p[0] as string)\n p[p.length - 1] += '{' + body + '}'\n\n if (!post.length) {\n pushAll(parts, p)\n return parts\n }\n\n carry = p.pop() as string\n pushAll(parts, p)\n str = post\n }\n}\n\nexport type BraceExpansionOptions = {\n max?: number\n maxLength?: number\n maxDepth?: number\n maxRewrites?: number\n maxSteps?: number\n}\n\n// An option that is left out, or that is NaN, gets its default. Every\n// comparison against NaN is false, so a NaN bound would never be reached:\n// `{ maxSteps: NaN }` let 15KB of input block the event loop for 16 seconds,\n// and `{ maxDepth: NaN }` overflowed the stack again (CVE-2026-102278). Pass\n// `Infinity` to lift a bound.\nfunction bound(value: number | undefined, fallback: number) {\n return value === undefined || isNaN(value) ? fallback : value\n}\n\nexport function expand(str: string, options: BraceExpansionOptions = {}) {\n if (!str) {\n return []\n }\n\n const max = bound(options.max, EXPANSION_MAX)\n const maxLength = bound(options.maxLength, EXPANSION_MAX_LENGTH)\n const maxDepth = bound(options.maxDepth, EXPANSION_MAX_DEPTH)\n const maxRewrites = bound(options.maxRewrites, EXPANSION_MAX_REWRITES)\n const maxSteps = bound(options.maxSteps, EXPANSION_MAX_STEPS)\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(\n escapeBraces(str),\n max,\n maxLength,\n maxDepth,\n 0,\n maxRewrites,\n { remaining: maxSteps },\n true,\n ).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\n// Build `{ acc[a] + pre + values[v] }` for every combination, capping the\n// number of results at `max` and the total number of characters at `maxLength`.\n// This is the one place output grows, so bounding it here keeps the single\n// accumulator - and therefore memory - flat regardless of how many brace groups\n// are combined (CVE-2026-14257). Each result built is a step, since `max` and\n// `maxLength` bound one combination, not how many brace groups are combined.\nfunction combine(\n acc: string[],\n pre: string,\n values: string[],\n max: number,\n maxLength: number,\n dropEmpties: boolean,\n budget: Budget,\n): string[] {\n const out: string[] = []\n let length = 0\n // Bash drops empty results at the top level, and they don't count against\n // `max`, so `max` bounds the number of *kept* results. Only an empty\n // `acc[a] + pre` can make one, so for those the empty values are skipped\n // without being visited. Visiting them one at a time let a set of empties\n // cost `acc.length * values.length` while keeping nothing.\n let nonEmpty: string[] | undefined\n outer: for (let a = 0; a < acc.length; a++) {\n const prefix = (acc[a] as string) + pre\n let vs = values\n if (dropEmpties && !prefix) {\n if (!nonEmpty) nonEmpty = values.filter(v => v)\n vs = nonEmpty\n }\n for (let v = 0; v < vs.length; v++) {\n if (out.length >= max) break outer\n const expansion = prefix + vs[v]\n if (length + expansion.length > maxLength) break outer\n out.push(expansion)\n length += expansion.length\n }\n }\n budget.remaining -= out.length\n return out\n}\n\n// The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)\n// sequence body, or `undefined` if the step budget runs out generating them.\nfunction expandSequence(\n body: string,\n isAlphaSequence: boolean,\n max: number,\n maxLength: number,\n budget: Budget,\n): string[] | undefined {\n const n = body.split(/\\.\\./)\n const N: string[] = []\n // A sequence body always splits into two or three parts, but the compiler\n // can't know that.\n /* c8 ignore start */\n if (n[0] === undefined || n[1] === undefined) {\n return N\n }\n /* c8 ignore stop */\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ?\n Math.max(Math.abs(numeric(n[2])), 1)\n : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n // A padded value is built a character at a time to `width`, which the input\n // sets, so it costs one step per character: 64KB of\n // `('{' + '0'.repeat(100) + '..99999}').repeat(n)` took 7 seconds charged\n // one step per value.\n const cost = pad ? width : 1\n\n let length = 0\n for (let i = x; test(i, y) && N.length < max; i += incr) {\n // Each value is a step. `max` and `maxLength` bound one sequence, but a\n // chain of them still generated up to `max` values each, however few\n // combining could keep.\n budget.remaining -= cost\n if (budget.remaining < 0) {\n return undefined\n }\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n if (length + c.length > maxLength) break\n N.push(c)\n length += c.length\n }\n return N\n}\n\nfunction expand_(\n str: string,\n max: number,\n maxLength: number,\n maxDepth: number,\n depth: number,\n maxRewrites: number,\n budget: Budget,\n isTop: boolean,\n): string[] {\n // An overdraft here makes the first scan refuse, so `str` stays literal.\n budget.remaining -= CALL_STEPS\n\n // Too deeply nested to keep following: treat the rest as literal, the same\n // way a group that cannot expand is already handled. Truncating rather than\n // throwing keeps `expand` total, matching `max` and `maxLength`.\n if (depth > maxDepth) {\n return [str]\n }\n\n // Consume the string's top-level brace groups left to right, threading a\n // running set of combined prefixes (`acc`). Expanding the tail iteratively -\n // rather than recursing on `m.post` once per group - keeps the native stack\n // depth constant, so deeply chained input (`'{a,b}'.repeat(3000)`) can no\n // longer overflow the stack, and leaves a single accumulator whose size\n // `maxLength` bounds directly (CVE-2026-14257).\n let acc: string[] = ['']\n\n // Bash drops empty results, but only when the *first* top-level group is a\n // comma set - a sequence like `{a..\\}` may legitimately yield ''. The drop\n // is on the final strings, so it is applied to whichever `combine` produces\n // them (the one with no brace set left in the tail).\n // How many times the `{a},b}` rewrite below has restarted the scan. Each pass\n // re-reads the whole string, so leaving this unbounded is quadratic.\n let rewrites = 0\n let dropEmpties = false\n let firstGroup = true\n // `str` with its unmatched `{` masked, once a scan has run into them\n let masked = str\n\n for (;;) {\n const m = balancedWithBudget(str, masked, budget)\n\n // No brace set left, or no step budget left to look for one: the rest of\n // the string is literal.\n if (!m) {\n return combine(acc, str, [''], max, maxLength, dropEmpties, budget)\n }\n if (m.unmatched) {\n masked = maskUnmatchedOpens(masked, budget)\n }\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n\n // This set and the rest of the string, literal: for a set that cannot\n // expand, and for one the step budget runs out on. Once it is overdrawn,\n // every set still being expanded, at every level, stays literal like this -\n // otherwise each level above would go on combining, and wrapping and\n // expanding again, results the budget was too small for.\n const literal = () =>\n combine(\n acc,\n pre + '{' + m.body + '}' + m.post,\n [''],\n max,\n maxLength,\n dropEmpties,\n budget,\n )\n\n if (/\\$$/.test(pre)) {\n acc = combine(\n acc,\n pre + '{' + m.body + '}',\n [''],\n max,\n maxLength,\n dropEmpties && !m.post.length,\n budget,\n )\n firstGroup = false\n if (!m.post.length) break\n str = m.post\n masked = masked.slice(m.end + 1)\n continue\n }\n\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(\n m.body,\n )\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (rewrites < maxRewrites && commaSetFollows(m.post, budget)) {\n rewrites++\n str = m.pre + '{' + m.body + escClose + m.post\n // Taking a `}` away never gives an unmatched `{` a partner, so what\n // is masked stays unmatched. The `{` it closed can be left without\n // one, and the next scan masks it.\n masked =\n masked.slice(0, m.end) + escClose + masked.slice(m.end + 1)\n isTop = true\n continue\n }\n // Nothing here expands, so the whole remaining string is literal.\n return literal()\n }\n\n if (firstGroup) {\n dropEmpties = isTop && !isSequence\n firstGroup = false\n }\n\n let values: string[] | undefined\n if (isSequence) {\n values = expandSequence(\n m.body,\n isAlphaSequence,\n max,\n maxLength,\n budget,\n )\n if (!values) {\n return literal()\n }\n } else {\n let n = parseCommaParts(m.body, budget)\n // The step budget ran out partway through the set.\n if (!n) {\n return literal()\n }\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(\n n[0],\n max,\n maxLength,\n maxDepth,\n depth + 1,\n maxRewrites,\n budget,\n false,\n ).map(embrace)\n // The step budget ran out expanding the set's only part.\n if (budget.remaining < 0) {\n return literal()\n }\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n const next = combine(\n acc,\n pre + n[0],\n [''],\n max,\n maxLength,\n dropEmpties && !m.post.length,\n budget,\n )\n if (budget.remaining < 0) {\n return literal()\n }\n acc = next\n if (!m.post.length) break\n str = m.post\n masked = masked.slice(m.end + 1)\n continue\n }\n /* c8 ignore stop */\n }\n\n // Values that `combine` is going to drop as empty produce no result, so\n // they must not count against `max` - otherwise `{a,,b}` with `max: 2`\n // would stop at `['a', '']` and yield one result instead of two. Skipping\n // them outright keeps `values` bounded while leaving `max` a bound on\n // *kept* results.\n let dropsEmpties = dropEmpties && !m.post.length && !pre\n for (let d = 0; dropsEmpties && d < acc.length; d++) {\n if (acc[d]) {\n dropsEmpties = false\n }\n }\n\n values = []\n let valuesLength = 0\n outer: for (let j = 0; j < n.length; j++) {\n const expanded = expand_(\n n[j] as string,\n max,\n maxLength,\n maxDepth,\n depth + 1,\n maxRewrites,\n budget,\n false,\n )\n // The step budget ran out expanding a member.\n if (budget.remaining < 0) {\n return literal()\n }\n for (let k = 0; k < expanded.length; k++) {\n const v = expanded[k] as string\n if (dropsEmpties && !v) continue\n if (\n values.length >= max ||\n valuesLength + v.length > maxLength\n ) {\n break outer\n }\n values.push(v)\n valuesLength += v.length\n }\n }\n }\n\n const next = combine(\n acc,\n pre,\n values,\n max,\n maxLength,\n dropEmpties && !m.post.length,\n budget,\n )\n // The step budget ran out combining the set's values in.\n if (budget.remaining < 0) {\n return literal()\n }\n acc = next\n if (!m.post.length) break\n str = m.post\n masked = masked.slice(m.end + 1)\n }\n\n return acc\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/brace-expansion/package.json b/mac/patchers/desktop/node_modules/brace-expansion/package.json index a5c96ebe02f5f9c6c4216616ded0e81fcba53622..b4ca7ccfc895b335a15fae5bc9c6a12e5d63448a 100644 --- a/mac/patchers/desktop/node_modules/brace-expansion/package.json +++ b/mac/patchers/desktop/node_modules/brace-expansion/package.json @@ -1,7 +1,7 @@ { "name": "brace-expansion", "description": "Brace expansion as known from sh/bash", - "version": "5.0.12", + "version": "5.0.13", "files": [ "dist" ], diff --git a/mac/patchers/desktop/node_modules/glob/README.md b/mac/patchers/desktop/node_modules/glob/README.md index 1de5ba27839e6ab19040affa94873363354d59cc..859835eb243c44aba004fa68c4d01082ce419bd3 100644 --- a/mac/patchers/desktop/node_modules/glob/README.md +++ b/mac/patchers/desktop/node_modules/glob/README.md @@ -2,9 +2,10 @@ Match files using the patterns the shell uses. -The most correct and second fastest glob implementation in -JavaScript. (See [**Comparison to Other JavaScript Glob -Implementations**](#comparisons-to-other-fnmatchglob-implementations) +The safest ([no ReDoS](#redos-protection)), most correct, and +second fastest glob implementation in JavaScript. (See +[**Comparison to Other JavaScript Glob +Implementations**](#comparison-to-other-javascript-glob-implementations) at the bottom of this readme.) ![a fun cartoon logo made of glob @@ -325,17 +326,17 @@ share the previously loaded cache. _always_ start in the `x:/` or `//host/share` directory, regardless of the `root` setting. -> [!NOTE] This _doesn't_ necessarily limit the walk to the -> `root` directory, and doesn't affect the cwd starting point -> for non-absolute patterns. A pattern containing `..` will -> still be able to traverse out of the root directory, if it -> is not an actual root directory on the filesystem, and any -> non-absolute patterns will be matched in the `cwd`. For -> example, the pattern `/../*` with `{root:'/some/path'}` -> will return all files in `/some`, not all files in -> `/some/path`. The pattern `*` with `{root:'/some/path'}` -> will return all the entries in the cwd, not the entries in -> `/some/path`. +> [!NOTE] +> This _doesn't_ necessarily limit the walk to the `root` +> directory, and doesn't affect the cwd starting point for +> non-absolute patterns. A pattern containing `..` will still be +> able to traverse out of the root directory, if it is not an +> actual root directory on the filesystem, and any non-absolute +> patterns will be matched in the `cwd`. For example, the pattern +> `/../*` with `{root:'/some/path'}` will return all files in +> `/some`, not all files in `/some/path`. The pattern `*` with +> `{root:'/some/path'}` will return all the entries in the cwd, +> not the entries in `/some/path`. - `windowsPathsNoEscape` Use `\\` as a path separator _only_, and _never_ as an escape character. If set, all `\\` characters are @@ -381,6 +382,17 @@ share the previously loaded cache. - `noext` Do not match "extglob" patterns such as `+(a|b)`. +- `normalize` Normalize unicode in the pattern, and in the file + names that it is matched against, with this form: `'NFC'`, + `'NFD'`, `'NFKC'`, or `'NFKD'`. `true` means `'NFC'`. A char + such as `é` can be one code point, or `e` followed by a + combining accent, and some file systems (such as on macOS) can + give names in either form. This is passed to minimatch, so it + applies to the portions of the pattern with magic, and to the + `ignore` patterns. The portions of the pattern without magic + are looked up with path-scurry, which already compares the + names of the entries that it knows in their `'NFKD'` form. + - `nocase` Perform a case-insensitive match. This defaults to `true` on macOS and Windows systems, and `false` on all others. @@ -391,9 +403,9 @@ share the previously loaded cache. > `false` on case-insensitive file systems, then the walk may > return more or less results than expected. > -> As a shortcut to avoid excessive `RegExp` creations, `Glob` -> will use string portions as-is to `readdir()` calls while doing -> its traversal. If you are setting a `nocase: true` match on a +> As a shortcut, `Glob` will use string portions as-is to +> `readdir()` calls while doing its traversal, in place of making +> a case-insensitive matcher for each of them. If you are setting a `nocase: true` match on a > file system that is in fact case sensitive, then this will > result in matches not being found that you might expect, > because for example the pattern `Foo/*` will fail to read the @@ -440,6 +452,8 @@ share the previously loaded cache. a glob pattern or array of glob patterns to exclude from matches. To ignore all children within a directory, as well as the entry itself, append `'/**'` to the ignore pattern. + Ignore patterns that start with `/` start at the same place as + other patterns that start with `/` (see the `root` option). If an object is provided that has `ignored(path)` and/or `childrenIgnored(path)` methods, then these methods will be @@ -544,9 +558,9 @@ share the previously loaded cache. // likely to match first, since it's just a stat 'a/b/c/d/e/f', - // this pattern is more complicated! It must to various readdir() - // calls and test the results against a regular expression, and that - // is certainly going to take a little bit longer. + // this pattern is more complicated! It must do various readdir() + // calls and test the results against the pattern, and that is + // certainly going to take a little bit longer. // // So, later on, it encounters a match at 'a/b/c/d/e', but it's too // late to ignore a/b/c/d/e/f, because it's already been emitted. @@ -562,12 +576,12 @@ share the previously loaded cache. included child entry will not cause problems. > [!NOTE] -> It _only_ ignores matches that would be a descendant -> of a previous match, and only if that descendant is matched -> _after_ the ancestor is encountered. Since the file system walk -> happens in indeterminate order, it's possible that a match will -> already be added before its ancestor, if multiple or braced -> patterns are used. +> It _only_ ignores matches that would be a descendant of a +> previous match, and only if that descendant is matched _after_ +> the ancestor is encountered. Since the file system walk happens +> in indeterminate order, it's possible that a match will already +> be added before its ancestor, if multiple or braced patterns +> are used. - `braceExpandMax` number, defaults to `10_000`. This is the maximum number of `{x,y,...}` patterns to expand. It is very @@ -632,9 +646,8 @@ path separators (ie, `/` on all platforms, and `\` on Windows). ### Dots If a file or directory path portion has a `.` as the first -character, then it will not match any glob pattern unless that -pattern's corresponding path part also has a `.` as its first -character. +character, then it will only match a portion of the pattern if a +literal `.` in the pattern matches that first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does @@ -674,9 +687,9 @@ it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. > [!NOTE] -> Symlinked directories are not traversed as part of a -> `**`, though their contents may match against subsequent portions -> of the pattern. This prevents infinite loops and duplicates and +> Symlinked directories are not traversed as part of a `**`, +> though their contents may match against subsequent portions of +> the pattern. This prevents infinite loops and duplicates and > the like. You can force glob to traverse symlinks with `**` by > setting `{follow:true}` in the options. @@ -696,6 +709,28 @@ classes) style class patterns are supported and Unicode-aware, but `[=c=]` (locale-specific character collation weight), and `[.symbol.]` (collating symbol), are not. +Each portion of a pattern is matched by +[minimatch](https://github.com/isaacs/minimatch), with Bash 5 as +the reference, and patterns are never compiled to regular +expressions. These are the known differences from Bash: + +- If `dot` is not set, a portion of a pattern can match a file + name that starts with `.` when extglobs before a literal `.` + match the empty string. For example, `@(|x).*` matches `.a`. + Bash does not match these dotfiles. +- If an extglob such as `?(a` is not closed, Bash matches the + whole pattern as a literal string. In this module, only the + `?(` is literal, and the rest of the pattern is still matched + as a glob. +- A pattern is split into portions on every `/`, including a `/` + inside an extglob, so `@(a|b/c)/*` has an extglob that is not + closed. Bash keeps the extglob whole, and drops each alternative + with a `/` in it, as no file name can contain a `/`. So in Bash, + `@(a|b/c)/*` is the same as `@(a)/*`. +- With `nocase`, case is folded with Unicode simple case folding, + one code point at a time. Bash uses the case functions of the C + library for the current locale. + ### Repeated Slashes Unlike Bash and zsh, repeated `/` are always coalesced into a @@ -767,6 +802,56 @@ starts with `/`, then the traversal will run on the root of the drive provided as the `cwd` option. (That is, it is the result of `path.resolve('/')`.) +## ReDoS Protection + +Many glob implementations make a regular expression from each +pattern. A pattern such as `a*a*a*a*a*a*a*a*a*a*a`, tested against +a name such as `aaaaaaaaaaaaaaaaaaaaaaaaaaaaab` that does not +match, can make a backtracking regular expression engine try each +way that the `*` characters can split the name. The time that +this takes grows exponentially with the length of the name, so a +pattern from an untrusted source can stop a process for minutes +or more. This is a Regular Expression Denial of Service (ReDoS). + +This module never makes a regular expression from a pattern. +Each portion of a pattern between `/` characters that has magic +is matched by a `Matcher` from +[@isaacs/nonrecursive-glob-match](http://npm.im/@isaacs/nonrecursive-glob-match). +A `Matcher` is not a `RegExp`, and it does not backtrack. It tests +all of the ways that the pattern can match at the same time, in +one pass over the name, so no pattern can make it try the ways one +after another. The time to match a name grows no faster than its +length times the size of the portion of the pattern, for each +kind of pattern, including nested and negated extglobs such as +`+(a|*(b|!(c)))`. The pattern above matches or fails in about a +millisecond. + +The only regular expressions that a `Matcher` uses are for `[...]` +classes and case folding, and each of them only tests one +character at a time, so they can not backtrack over a name. + +These limits also apply: + +- The states that a `Matcher` reaches are cached, so that names + are matched faster, but the cache has a fixed size. When it is + full, it is cleared. +- Brace expansion makes no more than `braceExpandMax` patterns + (10,000 by default), so a pattern such as `{1..1000000}` can not + use an unbounded amount of memory. +- A pattern can have at most 65,536 characters. A longer pattern + throws an error. +- An `ignore` pattern with many `**` portions that are not next to + each other is matched with a limit on how deeply minimatch + recurses (200 by default). Past that limit, a path is not + treated as a match, so that path is not ignored. + +The time that a walk takes still depends on the file system. A +pattern such as `**` walks every directory under the `cwd`, so if +the patterns come from an untrusted source, set the `cwd` to the +folder that they can search, and use `maxDepth` and an abort +`signal` to limit the walk. Symbolic links to directories are not +followed by `**` unless the `follow` option is set. + ## Race Conditions Glob searching, by its very nature, is susceptible to race @@ -821,6 +906,10 @@ npm run test-regen # run the benchmarks npm run bench +# run the benchmarks in a Docker container that is limited to 4 +# CPUs and 8GB of memory, a few times, and print the medians +npm run bench:docker + # to profile javascript npm run prof ``` @@ -833,8 +922,8 @@ npm run prof Bash pattern expansion semantics, and as fast as possible within that constraint, _use this module_. - If you are reasonably sure that the patterns you will encounter - are relatively simple, and want the absolutely fastest glob - matcher out there, _use [fast-glob](http://npm.im/fast-glob)_. + are relatively simple, and want the fastest sync glob matcher + out there, _use [fast-glob](http://npm.im/fast-glob)_. - If you are reasonably sure that the patterns you will encounter are relatively simple, and want the convenience of automatically respecting `.gitignore` files, _use @@ -855,15 +944,17 @@ benefits and drawbacks. Both have very nice APIs and are reasonably fast. -`fast-glob` is, as far as I am aware, the fastest glob +`fast-glob` is, as far as I am aware, the fastest sync glob implementation in JavaScript today. However, there are many cases where the choices that `fast-glob` makes in pursuit of speed mean that its results differ from the results returned by Bash and other sh-like shells, which may be surprising. -In my testing, `fast-glob` is around 10-20% faster than this -module when walking over 200k files nested 4 directories -deep[1](#fn-webscale). However, there are some inconsistencies +In the [benchmarks below](#benchmark-results), which walk over +200k files nested 4 directories deep, the sync `fast-glob` takes +about 25% less time than this module, and the async `fast-glob` +takes about 5% more, for the patterns where they return the same +results[1](#fn-webscale). However, there are some inconsistencies with Bash matching behavior that this module does not suffer from: @@ -878,10 +969,12 @@ from: - Extglob patterns are allowed to contain `/` characters. Globby exhibits all of the same pattern semantics as fast-glob, -(as it is a wrapper around fast-glob) and is slightly slower than -node-glob (by about 10-20% in the benchmark test set, or in other -words, anywhere from 20-50% slower than fast-glob). However, it -adds some API conveniences that may be worth the costs. +(as it is a wrapper around fast-glob). In the benchmarks below, +the sync `globby` takes about 10% less time than this module, and +the async `globby` takes about 15% more, for the patterns where +they return the same results. It takes about 10-20% more time +than `fast-glob`. However, it adds some API conveniences that may +be worth the costs. - Support for `.gitignore` and other ignore files. - Support for negated globs (ie, patterns starting with `!` @@ -908,296 +1001,377 @@ course. ### Benchmark Results +These are from `npm run bench:docker`, which runs the benchmarks +in a Linux Docker container that is limited to 4 CPUs and 8GB of +memory, with the test files in memory. Each time is the median of +3 runs, and includes starting node. + The first number is time, smaller is better. -The second number is the count of results returned. +The second number is the count of results returned. The totals at +the end are over all of the patterns, including the ones where the +implementations return different results. ``` +--- pattern: '{0000,0,1111,1}/{0000,0,1111,1}/{0000,0,1111,1}/**' --- +~~ sync ~~ +fast-glob sync 0m0.046s 1600 +globby sync 0m0.050s 1600 +fs.globSync 0m0.040s 1776 +current globSync mjs 0m0.048s 1776 +current glob syncStream 0m0.046s 1776 +~~ async ~~ +fast-glob async 0m0.047s 1600 +globby async 0m0.053s 1600 +fs.glob 0m0.054s 1776 +current glob async mjs 0m0.050s 1776 +current glob stream 0m0.051s 1776 + --- pattern: '**' --- ~~ sync ~~ -node fast-glob sync 0m0.598s 200364 -node globby sync 0m0.765s 200364 -node current globSync mjs 0m0.683s 222656 -node current glob syncStream 0m0.649s 222656 +fast-glob sync 0m0.340s 200002 +globby sync 0m0.423s 200002 +fs.globSync 0m0.692s 222223 +current globSync mjs 0m0.437s 222223 +current glob syncStream 0m0.408s 222223 ~~ async ~~ -node fast-glob async 0m0.350s 200364 -node globby async 0m0.509s 200364 -node current glob async mjs 0m0.463s 222656 -node current glob stream 0m0.411s 222656 +fast-glob async 0m0.491s 200002 +globby async 0m0.569s 200002 +fs.glob 0m1.889s 222223 +current glob async mjs 0m0.464s 222223 +current glob stream 0m0.442s 222223 --- pattern: '**/..' --- ~~ sync ~~ -node fast-glob sync 0m0.486s 0 -node globby sync 0m0.769s 200364 -node current globSync mjs 0m0.564s 2242 -node current glob syncStream 0m0.583s 2242 +fast-glob sync 0m0.260s 0 +globby sync 0m0.432s 200002 +fs.globSync 0m0.531s 2222 +current globSync mjs 0m0.351s 2222 +current glob syncStream 0m0.347s 2222 ~~ async ~~ -node fast-glob async 0m0.283s 0 -node globby async 0m0.512s 200364 -node current glob async mjs 0m0.299s 2242 -node current glob stream 0m0.312s 2242 +fast-glob async 0m0.381s 0 +globby async 0m0.569s 200002 +fs.glob 0m1.632s 2222 +current glob async mjs 0m0.373s 2222 +current glob stream 0m0.366s 2222 --- pattern: './**/0/**/0/**/0/**/0/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.490s 10 -node globby sync 0m0.517s 10 -node current globSync mjs 0m0.540s 10 -node current glob syncStream 0m0.550s 10 +fast-glob sync 0m0.263s 10 +globby sync 0m0.267s 10 +fs.globSync 0m0.547s 10 +current globSync mjs 0m0.335s 10 +current glob syncStream 0m0.334s 10 ~~ async ~~ -node fast-glob async 0m0.290s 10 -node globby async 0m0.296s 10 -node current glob async mjs 0m0.278s 10 -node current glob stream 0m0.302s 10 +fast-glob async 0m0.374s 10 +globby async 0m0.388s 10 +fs.glob 0m1.676s 10 +current glob async mjs 0m0.342s 10 +current glob stream 0m0.340s 10 --- pattern: './**/[01]/**/[12]/**/[23]/**/[45]/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.500s 160 -node globby sync 0m0.528s 160 -node current globSync mjs 0m0.556s 160 -node current glob syncStream 0m0.573s 160 +fast-glob sync 0m0.270s 160 +globby sync 0m0.269s 160 +fs.globSync 0m0.588s 160 +current globSync mjs 0m0.344s 160 +current glob syncStream 0m0.348s 160 ~~ async ~~ -node fast-glob async 0m0.283s 160 -node globby async 0m0.301s 160 -node current glob async mjs 0m0.306s 160 -node current glob stream 0m0.322s 160 +fast-glob async 0m0.380s 160 +globby async 0m0.401s 160 +fs.glob 0m1.715s 160 +current glob async mjs 0m0.346s 160 +current glob stream 0m0.345s 160 --- pattern: './**/0/**/0/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.502s 5230 -node globby sync 0m0.527s 5230 -node current globSync mjs 0m0.544s 5230 -node current glob syncStream 0m0.557s 5230 +fast-glob sync 0m0.269s 5230 +globby sync 0m0.276s 5230 +fs.globSync 0m0.555s 5230 +current globSync mjs 0m0.343s 5230 +current glob syncStream 0m0.340s 5230 ~~ async ~~ -node fast-glob async 0m0.285s 5230 -node globby async 0m0.305s 5230 -node current glob async mjs 0m0.304s 5230 -node current glob stream 0m0.310s 5230 +fast-glob async 0m0.381s 5230 +globby async 0m0.399s 5230 +fs.glob 0m1.662s 5230 +current glob async mjs 0m0.345s 5230 +current glob stream 0m0.344s 5230 --- pattern: '**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.580s 200023 -node globby sync 0m0.771s 200023 -node current globSync mjs 0m0.685s 200023 -node current glob syncStream 0m0.649s 200023 +fast-glob sync 0m0.336s 200000 +globby sync 0m0.425s 200000 +fs.globSync 0m0.697s 200000 +current globSync mjs 0m0.438s 200000 +current glob syncStream 0m0.411s 200000 ~~ async ~~ -node fast-glob async 0m0.349s 200023 -node globby async 0m0.509s 200023 -node current glob async mjs 0m0.427s 200023 -node current glob stream 0m0.388s 200023 +fast-glob async 0m0.489s 200000 +globby async 0m0.563s 200000 +fs.glob 0m1.866s 200000 +current glob async mjs 0m0.467s 200000 +current glob stream 0m0.429s 200000 --- pattern: '{**/*.txt,**/?/**/*.txt,**/?/**/?/**/*.txt,**/?/**/?/**/?/**/*.txt,**/?/**/?/**/?/**/?/**/*.txt}' --- ~~ sync ~~ -node fast-glob sync 0m0.589s 200023 -node globby sync 0m0.771s 200023 -node current globSync mjs 0m0.716s 200023 -node current glob syncStream 0m0.684s 200023 +fast-glob sync 0m0.339s 200000 +globby sync 0m0.428s 200000 +fs.globSync 0m1.093s 200000 +current globSync mjs 0m0.463s 200000 +current glob syncStream 0m0.436s 200000 ~~ async ~~ -node fast-glob async 0m0.351s 200023 -node globby async 0m0.518s 200023 -node current glob async mjs 0m0.462s 200023 -node current glob stream 0m0.468s 200023 +fast-glob async 0m0.485s 200000 +globby async 0m0.570s 200000 +fs.glob 0m2.303s 200000 +current glob async mjs 0m0.499s 200000 +current glob stream 0m0.480s 200000 --- pattern: '**/5555/0000/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.496s 1000 -node globby sync 0m0.519s 1000 -node current globSync mjs 0m0.539s 1000 -node current glob syncStream 0m0.567s 1000 +fast-glob sync 0m0.265s 1000 +globby sync 0m0.269s 1000 +fs.globSync 0m0.525s 1000 +current globSync mjs 0m0.356s 1000 +current glob syncStream 0m0.360s 1000 ~~ async ~~ -node fast-glob async 0m0.285s 1000 -node globby async 0m0.299s 1000 -node current glob async mjs 0m0.305s 1000 -node current glob stream 0m0.301s 1000 +fast-glob async 0m0.375s 1000 +globby async 0m0.383s 1000 +fs.glob 0m1.592s 1000 +current glob async mjs 0m0.361s 1000 +current glob stream 0m0.366s 1000 --- pattern: './**/0/**/../[01]/**/0/../**/0/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.484s 0 -node globby sync 0m0.507s 0 -node current globSync mjs 0m0.577s 4880 -node current glob syncStream 0m0.586s 4880 +fast-glob sync 0m0.261s 0 +globby sync 0m0.263s 0 +fs.globSync 0m0.754s 4880 +current globSync mjs 0m0.351s 4880 +current glob syncStream 0m0.350s 4880 ~~ async ~~ -node fast-glob async 0m0.280s 0 -node globby async 0m0.298s 0 -node current glob async mjs 0m0.327s 4880 -node current glob stream 0m0.324s 4880 +fast-glob async 0m0.363s 0 +globby async 0m0.382s 0 +fs.glob 0m1.869s 4880 +current glob async mjs 0m0.370s 4880 +current glob stream 0m0.367s 4880 --- pattern: '**/????/????/????/????/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.547s 100000 -node globby sync 0m0.673s 100000 -node current globSync mjs 0m0.626s 100000 -node current glob syncStream 0m0.618s 100000 +fast-glob sync 0m0.297s 100000 +globby sync 0m0.349s 100000 +fs.globSync 0m0.681s 100000 +current globSync mjs 0m0.404s 100000 +current glob syncStream 0m0.399s 100000 ~~ async ~~ -node fast-glob async 0m0.315s 100000 -node globby async 0m0.414s 100000 -node current glob async mjs 0m0.366s 100000 -node current glob stream 0m0.345s 100000 +fast-glob async 0m0.440s 100000 +globby async 0m0.484s 100000 +fs.glob 0m1.805s 100000 +current glob async mjs 0m0.418s 100000 +current glob stream 0m0.413s 100000 --- pattern: './{**/?{/**/?{/**/?{/**/?,,,,},,,,},,,,},,,}/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.588s 100000 -node globby sync 0m0.670s 100000 -node current globSync mjs 0m0.717s 200023 -node current glob syncStream 0m0.687s 200023 +fast-glob sync 0m0.337s 200000 +globby sync 0m0.427s 200000 +fs.globSync 0m1.264s 200000 +current globSync mjs 0m0.465s 200000 +current glob syncStream 0m0.446s 200000 ~~ async ~~ -node fast-glob async 0m0.343s 100000 -node globby async 0m0.418s 100000 -node current glob async mjs 0m0.519s 200023 -node current glob stream 0m0.451s 200023 +fast-glob async 0m0.491s 200000 +globby async 0m0.562s 200000 +fs.glob 0m2.508s 200000 +current glob async mjs 0m0.494s 200000 +current glob stream 0m0.473s 200000 --- pattern: '**/!(0|9).txt' --- ~~ sync ~~ -node fast-glob sync 0m0.573s 160023 -node globby sync 0m0.731s 160023 -node current globSync mjs 0m0.680s 180023 -node current glob syncStream 0m0.659s 180023 +fast-glob sync 0m0.327s 160000 +globby sync 0m0.404s 160000 +fs.globSync 0m0.687s 180000 +current globSync mjs 0m0.462s 180000 +current glob syncStream 0m0.418s 180000 ~~ async ~~ -node fast-glob async 0m0.345s 160023 -node globby async 0m0.476s 160023 -node current glob async mjs 0m0.427s 180023 -node current glob stream 0m0.388s 180023 +fast-glob async 0m0.474s 160000 +globby async 0m0.552s 160000 +fs.glob 0m1.876s 180000 +current glob async mjs 0m0.465s 180000 +current glob stream 0m0.436s 180000 --- pattern: './{*/**/../{*/**/../{*/**/../{*/**/../{*/**,,,,},,,,},,,,},,,,},,,,}/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.483s 0 -node globby sync 0m0.512s 0 -node current globSync mjs 0m0.811s 200023 -node current glob syncStream 0m0.773s 200023 +fast-glob sync 0m0.262s 0 +globby sync 0m0.264s 0 +fs.globSync 0m0.933s 200000 +current globSync mjs 0m0.557s 200000 +current glob syncStream 0m0.541s 200000 ~~ async ~~ -node fast-glob async 0m0.280s 0 -node globby async 0m0.299s 0 -node current glob async mjs 0m0.617s 200023 -node current glob stream 0m0.568s 200023 +fast-glob async 0m0.377s 0 +globby async 0m0.414s 0 +fs.glob 0m2.135s 200000 +current glob async mjs 0m0.662s 200000 +current glob stream 0m0.639s 200000 --- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.485s 0 -node globby sync 0m0.507s 0 -node current globSync mjs 0m0.759s 200023 -node current glob syncStream 0m0.740s 200023 +fast-glob sync 0m0.256s 0 +globby sync 0m0.262s 0 +fs.globSync 0m0.716s 200000 +current globSync mjs 0m0.519s 200000 +current glob syncStream 0m0.494s 200000 ~~ async ~~ -node fast-glob async 0m0.281s 0 -node globby async 0m0.297s 0 -node current glob async mjs 0m0.544s 200023 -node current glob stream 0m0.464s 200023 +fast-glob async 0m0.363s 0 +globby async 0m0.374s 0 +fs.glob 0m1.870s 200000 +current glob async mjs 0m0.565s 200000 +current glob stream 0m0.542s 200000 --- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.486s 0 -node globby sync 0m0.513s 0 -node current globSync mjs 0m0.734s 200023 -node current glob syncStream 0m0.696s 200023 +fast-glob sync 0m0.259s 0 +globby sync 0m0.262s 0 +fs.globSync 0m0.725s 200000 +current globSync mjs 0m0.488s 200000 +current glob syncStream 0m0.459s 200000 ~~ async ~~ -node fast-glob async 0m0.286s 0 -node globby async 0m0.296s 0 -node current glob async mjs 0m0.506s 200023 -node current glob stream 0m0.483s 200023 +fast-glob async 0m0.366s 0 +globby async 0m0.379s 0 +fs.glob 0m1.878s 200000 +current glob async mjs 0m0.522s 200000 +current glob stream 0m0.495s 200000 --- pattern: './0/**/../1/**/../2/**/../3/**/../4/**/../5/**/../6/**/../7/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.060s 0 -node globby sync 0m0.074s 0 -node current globSync mjs 0m0.067s 0 -node current glob syncStream 0m0.066s 0 +fast-glob sync 0m0.050s 0 +globby sync 0m0.055s 0 +fs.globSync 0m1.134s 28970 +current globSync mjs 0m0.290s 28970 +current glob syncStream 0m0.287s 28970 ~~ async ~~ -node fast-glob async 0m0.060s 0 -node globby async 0m0.075s 0 -node current glob async mjs 0m0.066s 0 -node current glob stream 0m0.067s 0 +fast-glob async 0m0.055s 0 +globby async 0m0.064s 0 +fs.glob 0m1.745s 28970 +current glob async mjs 0m0.307s 28970 +current glob stream 0m0.301s 28970 --- pattern: './**/?/**/?/**/?/**/?/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.568s 100000 -node globby sync 0m0.651s 100000 -node current globSync mjs 0m0.619s 100000 -node current glob syncStream 0m0.617s 100000 +fast-glob sync 0m0.305s 100000 +globby sync 0m0.353s 100000 +fs.globSync 0m0.750s 100000 +current globSync mjs 0m0.400s 100000 +current glob syncStream 0m0.403s 100000 ~~ async ~~ -node fast-glob async 0m0.332s 100000 -node globby async 0m0.409s 100000 -node current glob async mjs 0m0.372s 100000 -node current glob stream 0m0.351s 100000 +fast-glob async 0m0.466s 100000 +globby async 0m0.513s 100000 +fs.glob 0m1.900s 100000 +current glob async mjs 0m0.415s 100000 +current glob stream 0m0.412s 100000 --- pattern: '**/*/**/*/**/*/**/*/**' --- ~~ sync ~~ -node fast-glob sync 0m0.603s 200113 -node globby sync 0m0.798s 200113 -node current globSync mjs 0m0.730s 222137 -node current glob syncStream 0m0.693s 222137 +fast-glob sync 0m0.371s 200000 +globby sync 0m0.470s 200000 +fs.globSync 0m0.907s 220000 +current globSync mjs 0m0.476s 220000 +current glob syncStream 0m0.452s 220000 ~~ async ~~ -node fast-glob async 0m0.356s 200113 -node globby async 0m0.525s 200113 -node current glob async mjs 0m0.508s 222137 -node current glob stream 0m0.455s 222137 +fast-glob async 0m0.526s 200000 +globby async 0m0.611s 200000 +fs.glob 0m2.094s 220000 +current glob async mjs 0m0.521s 220000 +current glob stream 0m0.498s 220000 --- pattern: './**/*/**/*/**/*/**/*/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.622s 200000 -node globby sync 0m0.792s 200000 -node current globSync mjs 0m0.722s 200000 -node current glob syncStream 0m0.695s 200000 +fast-glob sync 0m0.367s 200000 +globby sync 0m0.459s 200000 +fs.globSync 0m0.911s 200000 +current globSync mjs 0m0.481s 200000 +current glob syncStream 0m0.454s 200000 ~~ async ~~ -node fast-glob async 0m0.369s 200000 -node globby async 0m0.527s 200000 -node current glob async mjs 0m0.502s 200000 -node current glob stream 0m0.481s 200000 +fast-glob async 0m0.519s 200000 +globby async 0m0.596s 200000 +fs.glob 0m2.140s 200000 +current glob async mjs 0m0.508s 200000 +current glob stream 0m0.483s 200000 --- pattern: '**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.588s 200023 -node globby sync 0m0.771s 200023 -node current globSync mjs 0m0.684s 200023 -node current glob syncStream 0m0.658s 200023 +fast-glob sync 0m0.336s 200000 +globby sync 0m0.425s 200000 +fs.globSync 0m0.698s 200000 +current globSync mjs 0m0.437s 200000 +current glob syncStream 0m0.430s 200000 ~~ async ~~ -node fast-glob async 0m0.352s 200023 -node globby async 0m0.516s 200023 -node current glob async mjs 0m0.432s 200023 -node current glob stream 0m0.384s 200023 +fast-glob async 0m0.483s 200000 +globby async 0m0.565s 200000 +fs.glob 0m1.874s 200000 +current glob async mjs 0m0.462s 200000 +current glob stream 0m0.468s 200000 --- pattern: './**/**/**/**/**/**/**/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.589s 200023 -node globby sync 0m0.766s 200023 -node current globSync mjs 0m0.682s 200023 -node current glob syncStream 0m0.652s 200023 +fast-glob sync 0m0.346s 200000 +globby sync 0m0.442s 200000 +fs.globSync 0m0.721s 200000 +current globSync mjs 0m0.437s 200000 +current glob syncStream 0m0.417s 200000 ~~ async ~~ -node fast-glob async 0m0.352s 200023 -node globby async 0m0.523s 200023 -node current glob async mjs 0m0.436s 200023 -node current glob stream 0m0.380s 200023 +fast-glob async 0m0.522s 200000 +globby async 0m0.595s 200000 +fs.glob 0m1.892s 200000 +current glob async mjs 0m0.486s 200000 +current glob stream 0m0.468s 200000 --- pattern: '**/*/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.592s 200023 -node globby sync 0m0.776s 200023 -node current globSync mjs 0m0.691s 200023 -node current glob syncStream 0m0.659s 200023 +fast-glob sync 0m0.343s 200000 +globby sync 0m0.434s 200000 +fs.globSync 0m0.753s 200000 +current globSync mjs 0m0.448s 200000 +current glob syncStream 0m0.446s 200000 ~~ async ~~ -node fast-glob async 0m0.357s 200023 -node globby async 0m0.513s 200023 -node current glob async mjs 0m0.471s 200023 -node current glob stream 0m0.424s 200023 +fast-glob async 0m0.516s 200000 +globby async 0m0.576s 200000 +fs.glob 0m1.936s 200000 +current glob async mjs 0m0.492s 200000 +current glob stream 0m0.465s 200000 --- pattern: '**/*/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.585s 200023 -node globby sync 0m0.766s 200023 -node current globSync mjs 0m0.694s 200023 -node current glob syncStream 0m0.664s 200023 +fast-glob sync 0m0.341s 200000 +globby sync 0m0.429s 200000 +fs.globSync 0m0.772s 200000 +current globSync mjs 0m0.451s 200000 +current glob syncStream 0m0.434s 200000 ~~ async ~~ -node fast-glob async 0m0.350s 200023 -node globby async 0m0.514s 200023 -node current glob async mjs 0m0.472s 200023 -node current glob stream 0m0.424s 200023 +fast-glob async 0m0.492s 200000 +globby async 0m0.565s 200000 +fs.glob 0m1.927s 200000 +current glob async mjs 0m0.480s 200000 +current glob stream 0m0.447s 200000 --- pattern: '**/[0-9]/**/*.txt' --- ~~ sync ~~ -node fast-glob sync 0m0.544s 100000 -node globby sync 0m0.636s 100000 -node current globSync mjs 0m0.626s 100000 -node current glob syncStream 0m0.621s 100000 +fast-glob sync 0m0.307s 100000 +globby sync 0m0.347s 100000 +fs.globSync 0m0.667s 100000 +current globSync mjs 0m0.393s 100000 +current glob syncStream 0m0.396s 100000 ~~ async ~~ -node fast-glob async 0m0.322s 100000 -node globby async 0m0.404s 100000 -node current glob async mjs 0m0.360s 100000 -node current glob stream 0m0.352s 100000 +fast-glob async 0m0.458s 100000 +globby async 0m0.490s 100000 +fs.glob 0m1.894s 100000 +current glob async mjs 0m0.433s 100000 +current glob stream 0m0.426s 100000 + +--- total of the medians --- +fast-glob sync (sync) 7.153s +globby sync (sync) 8.484s +fs.globSync (sync) 18.341s +current globSync mjs (sync) 10.174s +current glob syncStream (sync) 9.856s +fast-glob async (async) 10.314s +globby async (async) 11.617s +fs.glob (async) 45.732s +current glob async mjs (async) 10.847s +current glob stream (async) 10.496s ``` diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.d.ts b/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.d.ts index 85c1ccc263e7d3fb4685a50ff6b3531299246bd7..db4231afbb78ba7ed7988cbe30639ac1864e7e02 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.d.ts +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.d.ts @@ -1,7 +1,9 @@ +import type { Form } from 'minimatch'; import { Minimatch } from 'minimatch'; -import { Minipass } from 'minipass'; -import { FSOption, Path, PathScurry } from 'path-scurry'; -import { IgnoreLike } from './ignore.js'; +import type { Minipass } from 'minipass'; +import type { FSOption, Path } from 'path-scurry'; +import { PathScurry } from 'path-scurry'; +import type { IgnoreLike } from './ignore.js'; import { Pattern } from './pattern.js'; export type MatchSet = Minimatch['set']; export type GlobParts = Exclude; @@ -43,7 +45,7 @@ export interface GlobOptions { * The current working directory in which to search. Defaults to * `process.cwd()`. * - * May be eiher a string path or a `file://` URL object or string. + * May be either a string path or a `file://` URL object or string. */ cwd?: string | URL; /** @@ -89,7 +91,7 @@ export interface GlobOptions { * determine whether any Path is a match or if its children should be * traversed, respectively. */ - ignore?: string | string[] | IgnoreLike; + readonly ignore?: string | string[] | IgnoreLike | ReadonlyArray; /** * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no * effect if {@link nobrace} is set. @@ -139,6 +141,18 @@ export interface GlobOptions { * Do not match "extglob" patterns such as `+(a|b)`. */ noext?: boolean; + /** + * Normalize unicode in the pattern, and in the file names that it is + * matched against, with this form: `'NFC'`, `'NFD'`, `'NFKC'`, or + * `'NFKD'`. `true` means `'NFC'`. This is passed to minimatch, so it + * applies to the portions of the pattern with magic, and to the + * `ignore` patterns. + * + * The portions of the pattern without magic are looked up with + * path-scurry, which already compares the names of the entries + * that it knows in their `'NFKD'` form. + */ + normalize?: boolean | Form; /** * Do not match `**` against multiple filenames. (Ie, treat it as a normal * `*` instead.) @@ -232,11 +246,6 @@ export interface GlobOptions { * http://npm.im/path-scurry for details about what can be overridden. */ fs?: FSOption; - /** - * Just passed along to Minimatch. Note that this makes all pattern - * matching operations slower and *extremely* noisy. - */ - debug?: boolean; /** * Return `/` delimited paths, even on Windows. * @@ -324,7 +333,7 @@ export declare class Glob implements GlobOptions { dot: boolean; dotRelative: boolean; follow: boolean; - ignore?: string | string[] | IgnoreLike; + ignore?: string | string[] | IgnoreLike | ReadonlyArray; magicalBraces: boolean; mark?: boolean; matchBase: boolean; @@ -334,7 +343,7 @@ export declare class Glob implements GlobOptions { nodir: boolean; noext: boolean; noglobstar: boolean; - pattern: string[]; + pattern: string[] | ReadonlyArray; platform: NodeJS.Platform; realpath: boolean; scurry: PathScurry; diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.d.ts.map index b8d3c2596f067096f22a3bd1b59640fdd039c52c..19b6000016c53e84baef66073ed69ec68c6c418f 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.d.ts.map +++ b/mac/patchers/desktop/node_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/dist/commonjs/glob.js b/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.js index 2dcbd8a1d867cd59c97c7111d1796dda6ca8e84e..cf7c2721174564993f381fb5912ed2c3bcf1043e 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.js +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.js @@ -97,23 +97,21 @@ class Glob { if (this.withFileTypes && this.absolute !== undefined) { throw new Error('cannot set absolute and withFileTypes:true'); } - if (typeof pattern === 'string') { - pattern = [pattern]; - } + let p = typeof pattern === 'string' ? [pattern] : pattern; this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false; if (this.windowsPathsNoEscape) { - pattern = pattern.map(p => p.replace(/\\/g, '/')); + p = p.map(p => p.replace(/\\/g, '/')); } if (this.matchBase) { if (opts.noglobstar) { throw new TypeError('base matching requires globstar'); } - pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`)); + p = p.map(p => (p.includes('/') ? p : `./**/${p}`)); } - this.pattern = pattern; + this.pattern = p; this.platform = opts.platform || defaultPlatform; this.opts = { ...opts, platform: this.platform }; if (opts.scurry) { @@ -154,7 +152,6 @@ class Glob { optimizationLevel: 2, platform: this.platform, windowsPathsNoEscape: this.windowsPathsNoEscape, - debug: !!this.opts.debug, }; const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo)); const [matchSet, globParts] = mms.reduce((set, m) => { @@ -176,30 +173,26 @@ class Glob { // coerce them into the right shape. It will have already called // realpath() if the option was set to do so, so we know that's cached. // start out knowing the cwd, at least - return [ - ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { - ...this.opts, - maxDepth: this.maxDepth !== Infinity ? - this.maxDepth + this.scurry.cwd.depth() - : Infinity, - platform: this.platform, - nocase: this.nocase, - includeChildMatches: this.includeChildMatches, - }).walk()), - ]; + return await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).walk(); } walkSync() { - return [ - ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { - ...this.opts, - maxDepth: this.maxDepth !== Infinity ? - this.maxDepth + this.scurry.cwd.depth() - : Infinity, - platform: this.platform, - nocase: this.nocase, - includeChildMatches: this.includeChildMatches, - }).walkSync(), - ]; + return new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).walkSync(); } stream() { return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.js.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.js.map index 43406187c359192129642567da333a4c29968ae3..305464b89f6b4b27d58b119cc93d12762baa3c35 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.js.map +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/glob.js.map @@ -1 +1 @@ -{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":";;;AAAA,yCAAuD;AAEvD,uCAAwC;AACxC,6CAOoB;AAEpB,6CAAsC;AACtC,2CAAoD;AAKpD,4CAA4C;AAC5C,gDAAgD;AAChD,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAkWX;;GAEG;AACH,MAAa,IAAI;IACf,QAAQ,CAAU;IAClB,GAAG,CAAQ;IACX,IAAI,CAAS;IACb,GAAG,CAAS;IACZ,WAAW,CAAS;IACpB,MA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Q,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,UAAU,EAAE,CAAA;IACjB,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF;AA9QD,oBA8QC","sourcesContent":["import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n /**\n * Set to `true` to always receive absolute paths for\n * matched files. Set to `false` to always return relative paths.\n *\n * When this option is not set, absolute paths are returned for patterns\n * that are absolute, and otherwise paths are returned that are relative\n * to the `cwd` setting.\n *\n * This does _not_ make an extra system call to get\n * the realpath, it only does string path resolution.\n *\n * Conflicts with {@link withFileTypes}\n */\n absolute?: boolean\n\n /**\n * Set to false to enable {@link windowsPathsNoEscape}\n *\n * @deprecated\n */\n allowWindowsEscape?: boolean\n\n /**\n * The current working directory in which to search. Defaults to\n * `process.cwd()`.\n *\n * May be eiher a string path or a `file://` URL object or string.\n */\n cwd?: string | URL\n\n /**\n * Include `.dot` files in normal matches and `globstar`\n * matches. Note that an explicit dot in a portion of the pattern\n * will always match dot files.\n */\n dot?: boolean\n\n /**\n * Prepend all relative path strings with `./` (or `.\\` on Windows).\n *\n * Without this option, returned relative paths are \"bare\", so instead of\n * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n *\n * Relative patterns starting with `'../'` are not prepended with `./`, even\n * if this option is set.\n */\n dotRelative?: boolean\n\n /**\n * Follow symlinked directories when expanding `**`\n * patterns. This can result in a lot of duplicate references in\n * the presence of cyclic links, and make performance quite bad.\n *\n * By default, a `**` in a pattern will follow 1 symbolic link if\n * it is not the first item in the pattern, or none if it is the\n * first item in the pattern, following the same behavior as Bash.\n */\n follow?: boolean\n\n /**\n * string or string[], or an object with `ignored` and `childrenIgnored`\n * methods.\n *\n * If a string or string[] is provided, then this is treated as a glob\n * pattern or array of glob patterns to exclude from matches. To ignore all\n * children within a directory, as well as the entry itself, append `'/**'`\n * to the ignore pattern.\n *\n * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n * any other settings.\n *\n * If an object is provided that has `ignored(path)` and/or\n * `childrenIgnored(path)` methods, then these methods will be called to\n * determine whether any Path is a match or if its children should be\n * traversed, respectively.\n */\n ignore?: string | string[] | IgnoreLike\n\n /**\n * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n * effect if {@link nobrace} is set.\n *\n * Only has effect on the {@link hasMagic} function.\n */\n magicalBraces?: boolean\n\n /**\n * Add a `/` character to directory matches. Note that this requires\n * additional stat calls in some cases.\n */\n mark?: boolean\n\n /**\n * Perform a basename-only match if the pattern does not contain any slash\n * characters. That is, `*.js` would be treated as equivalent to\n * `**\\/*.js`, matching all js files in all directories.\n */\n matchBase?: boolean\n\n /**\n * Limit the directory traversal to a given depth below the cwd.\n * Note that this does NOT prevent traversal to sibling folders,\n * root patterns, and so on. It only limits the maximum folder depth\n * that the walk will descend, relative to the cwd.\n */\n maxDepth?: number\n\n /**\n * Do not expand `{a,b}` and `{1..3}` brace sets.\n */\n nobrace?: boolean\n\n /**\n * Perform a case-insensitive match. This defaults to `true` on macOS and\n * Windows systems, and `false` on all others.\n *\n * **Note** `nocase` should only be explicitly set when it is\n * known that the filesystem's case sensitivity differs from the\n * platform default. If set `true` on case-sensitive file\n * systems, or `false` on case-insensitive file systems, then the\n * walk may return more or less results than expected.\n */\n nocase?: boolean\n\n /**\n * Do not match directories, only files. (Note: to match\n * _only_ directories, put a `/` at the end of the pattern.)\n */\n nodir?: boolean\n\n /**\n * Do not match \"extglob\" patterns such as `+(a|b)`.\n */\n noext?: boolean\n\n /**\n * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n * `*` instead.)\n *\n * Conflicts with {@link matchBase}\n */\n noglobstar?: boolean\n\n /**\n * Defaults to value of `process.platform` if available, or `'linux'` if\n * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n * behavior.\n */\n platform?: NodeJS.Platform\n\n /**\n * Set to true to call `fs.realpath` on all of the\n * results. In the case of an entry that cannot be resolved, the\n * entry is omitted. This incurs a slight performance penalty, of\n * course, because of the added system calls.\n */\n realpath?: boolean\n\n /**\n *\n * A string path resolved against the `cwd` option, which\n * is used as the starting point for absolute patterns that start\n * with `/`, (but not drive letters or UNC paths on Windows).\n *\n * Note that this _doesn't_ necessarily limit the walk to the\n * `root` directory, and doesn't affect the cwd starting point for\n * non-absolute patterns. A pattern containing `..` will still be\n * able to traverse out of the root directory, if it is not an\n * actual root directory on the filesystem, and any non-absolute\n * patterns will be matched in the `cwd`. For example, the\n * pattern `/../*` with `{root:'/some/path'}` will return all\n * files in `/some`, not all files in `/some/path`. The pattern\n * `*` with `{root:'/some/path'}` will return all the entries in\n * the cwd, not the entries in `/some/path`.\n *\n * To start absolute and non-absolute patterns in the same\n * path, you can use `{root:''}`. However, be aware that on\n * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n * _always_ start in the `x:/` or `//host/share` directory,\n * regardless of the `root` setting.\n */\n root?: string\n\n /**\n * A [PathScurry](http://npm.im/path-scurry) object used\n * to traverse the file system. If the `nocase` option is set\n * explicitly, then any provided `scurry` object must match this\n * setting.\n */\n scurry?: PathScurry\n\n /**\n * Call `lstat()` on all entries, whether required or not to determine\n * if it's a valid match. When used with {@link withFileTypes}, this means\n * that matches will include data such as modified time, permissions, and\n * so on. Note that this will incur a performance cost due to the added\n * system calls.\n */\n stat?: boolean\n\n /**\n * An AbortSignal which will cancel the Glob walk when\n * triggered.\n */\n signal?: AbortSignal\n\n /**\n * Use `\\\\` as a path separator _only_, and\n * _never_ as an escape character. If set, all `\\\\` characters are\n * replaced with `/` in the pattern.\n *\n * Note that this makes it **impossible** to match against paths\n * containing literal glob pattern characters, but allows matching\n * with patterns constructed using `path.join()` and\n * `path.resolve()` on Windows platforms, mimicking the (buggy!)\n * behavior of Glob v7 and before on Windows. Please use with\n * caution, and be mindful of [the caveat below about Windows\n * paths](#windows). (For legacy reasons, this is also set if\n * `allowWindowsEscape` is set to the exact value `false`.)\n */\n windowsPathsNoEscape?: boolean\n\n /**\n * Return [PathScurry](http://npm.im/path-scurry)\n * `Path` objects instead of strings. These are similar to a\n * NodeJS `Dirent` object, but with additional methods and\n * properties.\n *\n * Conflicts with {@link absolute}\n */\n withFileTypes?: boolean\n\n /**\n * An fs implementation to override some or all of the defaults. See\n * http://npm.im/path-scurry for details about what can be overridden.\n */\n fs?: FSOption\n\n /**\n * Just passed along to Minimatch. Note that this makes all pattern\n * matching operations slower and *extremely* noisy.\n */\n debug?: boolean\n\n /**\n * Return `/` delimited paths, even on Windows.\n *\n * On posix systems, this has no effect. But, on Windows, it means that\n * paths will be `/` delimited, and absolute paths will be their full\n * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n * `'//?/C:/foo/bar'`\n */\n posix?: boolean\n\n /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: boolean\n\n /**\n * max number of `{...}` patterns to expand. Default `1_000`.\n *\n * Note: this is much less than minimatch's default of `100_000`,\n * because Glob has higher memory requirements due to walking\n * the file system tree.\n */\n braceExpandMax?: number\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n withFileTypes: true\n // string options not relevant if returning Path objects.\n absolute?: undefined\n mark?: undefined\n posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n withFileTypes?: undefined\n}\n\nexport type Result =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? false\n : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n absolute?: boolean\n cwd: string\n root?: string\n dot: boolean\n dotRelative: boolean\n follow: boolean\n ignore?: string | string[] | IgnoreLike\n magicalBraces: boolean\n mark?: boolean\n matchBase: boolean\n maxDepth: number\n nobrace: boolean\n nocase: boolean\n nodir: boolean\n noext: boolean\n noglobstar: boolean\n pattern: string[]\n platform: NodeJS.Platform\n realpath: boolean\n scurry: PathScurry\n stat: boolean\n signal?: AbortSignal\n windowsPathsNoEscape: boolean\n withFileTypes: FileTypes\n includeChildMatches: boolean\n\n /**\n * The options provided to the constructor.\n */\n opts: Opts\n\n /**\n * An array of parsed immutable {@link Pattern} objects.\n */\n patterns: Pattern[]\n\n /**\n * All options are stored as properties on the `Glob` object.\n *\n * See {@link GlobOptions} for full options descriptions.\n *\n * Note that a previous `Glob` object can be passed as the\n * `GlobOptions` to another `Glob` instantiation to re-use settings\n * and caches with a new pattern.\n *\n * Traversal functions can be called multiple times to run the walk\n * again.\n */\n constructor(pattern: string | string[], opts: Opts) {\n /* c8 ignore start */\n if (!opts) throw new TypeError('glob options required')\n /* c8 ignore stop */\n this.withFileTypes = !!opts.withFileTypes as FileTypes\n this.signal = opts.signal\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.dotRelative = !!opts.dotRelative\n this.nodir = !!opts.nodir\n this.mark = !!opts.mark\n if (!opts.cwd) {\n this.cwd = ''\n } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n opts.cwd = fileURLToPath(opts.cwd)\n }\n this.cwd = opts.cwd || ''\n this.root = opts.root\n this.magicalBraces = !!opts.magicalBraces\n this.nobrace = !!opts.nobrace\n this.noext = !!opts.noext\n this.realpath = !!opts.realpath\n this.absolute = opts.absolute\n this.includeChildMatches = opts.includeChildMatches !== false\n\n this.noglobstar = !!opts.noglobstar\n this.matchBase = !!opts.matchBase\n this.maxDepth =\n typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n this.stat = !!opts.stat\n this.ignore = opts.ignore\n\n if (this.withFileTypes && this.absolute !== undefined) {\n throw new Error('cannot set absolute and withFileTypes:true')\n }\n\n if (typeof pattern === 'string') {\n pattern = [pattern]\n }\n\n this.windowsPathsNoEscape =\n !!opts.windowsPathsNoEscape ||\n (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n false\n\n if (this.windowsPathsNoEscape) {\n pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n }\n\n if (this.matchBase) {\n if (opts.noglobstar) {\n throw new TypeError('base matching requires globstar')\n }\n pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n }\n\n this.pattern = pattern\n\n this.platform = opts.platform || defaultPlatform\n this.opts = { ...opts, platform: this.platform }\n if (opts.scurry) {\n this.scurry = opts.scurry\n if (\n opts.nocase !== undefined &&\n opts.nocase !== opts.scurry.nocase\n ) {\n throw new Error('nocase option contradicts provided scurry option')\n }\n } else {\n const Scurry =\n opts.platform === 'win32' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? PathScurryPosix\n : PathScurry\n this.scurry = new Scurry(this.cwd, {\n nocase: opts.nocase,\n fs: opts.fs,\n })\n }\n this.nocase = this.scurry.nocase\n\n // If you do nocase:true on a case-sensitive file system, then\n // we need to use regexps instead of strings for non-magic\n // path portions, because statting `aBc` won't return results\n // for the file `AbC` for example.\n const nocaseMagicOnly =\n this.platform === 'darwin' || this.platform === 'win32'\n\n const mmo: MinimatchOptions = {\n braceExpandMax: 10_000,\n ...opts,\n dot: this.dot,\n matchBase: this.matchBase,\n nobrace: this.nobrace,\n // default nocase based on platform\n nocase: this.nocase,\n nocaseMagicOnly,\n nocomment: true,\n noext: this.noext,\n nonegate: true,\n optimizationLevel: 2,\n platform: this.platform,\n windowsPathsNoEscape: this.windowsPathsNoEscape,\n debug: !!this.opts.debug,\n }\n\n const mms = this.pattern.map(p => new Minimatch(p, mmo))\n const [matchSet, globParts] = mms.reduce(\n (set: [MatchSet, GlobParts], m) => {\n set[0].push(...m.set)\n set[1].push(...m.globParts)\n return set\n },\n [[], []],\n )\n this.patterns = matchSet.map((set, i) => {\n const g = globParts[i]\n /* c8 ignore start */\n if (!g) throw new Error('invalid pattern object')\n /* c8 ignore stop */\n return new Pattern(set, g, 0, this.platform)\n })\n }\n\n /**\n * Returns a Promise that resolves to the results array.\n */\n async walk(): Promise>\n async walk(): Promise<(string | Path)[]> {\n // Walkers always return array of Path objects, so we just have to\n // coerce them into the right shape. It will have already called\n // realpath() if the option was set to do so, so we know that's cached.\n // start out knowing the cwd, at least\n return [\n ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walk()),\n ]\n }\n\n /**\n * synchronous {@link Glob.walk}\n */\n walkSync(): Results\n walkSync(): (string | Path)[] {\n return [\n ...new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walkSync(),\n ]\n }\n\n /**\n * Stream results asynchronously.\n */\n stream(): Minipass, Result>\n stream(): Minipass {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).stream()\n }\n\n /**\n * Stream results synchronously.\n */\n streamSync(): Minipass, Result>\n streamSync(): Minipass {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).streamSync()\n }\n\n /**\n * Default sync iteration function. Returns a Generator that\n * iterates over the results.\n */\n iterateSync(): Generator, void, void> {\n return this.streamSync()[Symbol.iterator]()\n }\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n /**\n * Default async iteration function. Returns an AsyncGenerator that\n * iterates over the results.\n */\n iterate(): AsyncGenerator, void, void> {\n return this.stream()[Symbol.asyncIterator]()\n }\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n}\n"]} \ No newline at end of file +{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":";;;AACA,yCAAqC;AAErC,uCAAwC;AAExC,6CAKoB;AAEpB,6CAAsC;AACtC,2CAAoD;AAKpD,4CAA4C;AAC5C,gDAAgD;AAChD,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;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D,GAAG,IAAI,CAAC,IAAI;YACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,UAAU,EAAE,CAAA;IACjB,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF;AAvQD,oBAuQC","sourcesContent":["import type { Form, MinimatchOptions } from 'minimatch'\nimport { Minimatch } from 'minimatch'\nimport type { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport type { FSOption, Path } from 'path-scurry'\nimport {\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\nimport type { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n /**\n * Set to `true` to always receive absolute paths for\n * matched files. Set to `false` to always return relative paths.\n *\n * When this option is not set, absolute paths are returned for patterns\n * that are absolute, and otherwise paths are returned that are relative\n * to the `cwd` setting.\n *\n * This does _not_ make an extra system call to get\n * the realpath, it only does string path resolution.\n *\n * Conflicts with {@link withFileTypes}\n */\n absolute?: boolean\n\n /**\n * Set to false to enable {@link windowsPathsNoEscape}\n *\n * @deprecated\n */\n allowWindowsEscape?: boolean\n\n /**\n * The current working directory in which to search. Defaults to\n * `process.cwd()`.\n *\n * May be either a string path or a `file://` URL object or string.\n */\n cwd?: string | URL\n\n /**\n * Include `.dot` files in normal matches and `globstar`\n * matches. Note that an explicit dot in a portion of the pattern\n * will always match dot files.\n */\n dot?: boolean\n\n /**\n * Prepend all relative path strings with `./` (or `.\\` on Windows).\n *\n * Without this option, returned relative paths are \"bare\", so instead of\n * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n *\n * Relative patterns starting with `'../'` are not prepended with `./`, even\n * if this option is set.\n */\n dotRelative?: boolean\n\n /**\n * Follow symlinked directories when expanding `**`\n * patterns. This can result in a lot of duplicate references in\n * the presence of cyclic links, and make performance quite bad.\n *\n * By default, a `**` in a pattern will follow 1 symbolic link if\n * it is not the first item in the pattern, or none if it is the\n * first item in the pattern, following the same behavior as Bash.\n */\n follow?: boolean\n\n /**\n * string or string[], or an object with `ignored` and `childrenIgnored`\n * methods.\n *\n * If a string or string[] is provided, then this is treated as a glob\n * pattern or array of glob patterns to exclude from matches. To ignore all\n * children within a directory, as well as the entry itself, append `'/**'`\n * to the ignore pattern.\n *\n * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n * any other settings.\n *\n * If an object is provided that has `ignored(path)` and/or\n * `childrenIgnored(path)` methods, then these methods will be called to\n * determine whether any Path is a match or if its children should be\n * traversed, respectively.\n */\n readonly ignore?: string | string[] | IgnoreLike | ReadonlyArray\n\n /**\n * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n * effect if {@link nobrace} is set.\n *\n * Only has effect on the {@link hasMagic} function.\n */\n magicalBraces?: boolean\n\n /**\n * Add a `/` character to directory matches. Note that this requires\n * additional stat calls in some cases.\n */\n mark?: boolean\n\n /**\n * Perform a basename-only match if the pattern does not contain any slash\n * characters. That is, `*.js` would be treated as equivalent to\n * `**\\/*.js`, matching all js files in all directories.\n */\n matchBase?: boolean\n\n /**\n * Limit the directory traversal to a given depth below the cwd.\n * Note that this does NOT prevent traversal to sibling folders,\n * root patterns, and so on. It only limits the maximum folder depth\n * that the walk will descend, relative to the cwd.\n */\n maxDepth?: number\n\n /**\n * Do not expand `{a,b}` and `{1..3}` brace sets.\n */\n nobrace?: boolean\n\n /**\n * Perform a case-insensitive match. This defaults to `true` on macOS and\n * Windows systems, and `false` on all others.\n *\n * **Note** `nocase` should only be explicitly set when it is\n * known that the filesystem's case sensitivity differs from the\n * platform default. If set `true` on case-sensitive file\n * systems, or `false` on case-insensitive file systems, then the\n * walk may return more or less results than expected.\n */\n nocase?: boolean\n\n /**\n * Do not match directories, only files. (Note: to match\n * _only_ directories, put a `/` at the end of the pattern.)\n */\n nodir?: boolean\n\n /**\n * Do not match \"extglob\" patterns such as `+(a|b)`.\n */\n noext?: boolean\n\n /**\n * Normalize unicode in the pattern, and in the file names that it is\n * matched against, with this form: `'NFC'`, `'NFD'`, `'NFKC'`, or\n * `'NFKD'`. `true` means `'NFC'`. This is passed to minimatch, so it\n * applies to the portions of the pattern with magic, and to the\n * `ignore` patterns.\n *\n * The portions of the pattern without magic are looked up with\n * path-scurry, which already compares the names of the entries\n * that it knows in their `'NFKD'` form.\n */\n normalize?: boolean | Form\n\n /**\n * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n * `*` instead.)\n *\n * Conflicts with {@link matchBase}\n */\n noglobstar?: boolean\n\n /**\n * Defaults to value of `process.platform` if available, or `'linux'` if\n * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n * behavior.\n */\n platform?: NodeJS.Platform\n\n /**\n * Set to true to call `fs.realpath` on all of the\n * results. In the case of an entry that cannot be resolved, the\n * entry is omitted. This incurs a slight performance penalty, of\n * course, because of the added system calls.\n */\n realpath?: boolean\n\n /**\n *\n * A string path resolved against the `cwd` option, which\n * is used as the starting point for absolute patterns that start\n * with `/`, (but not drive letters or UNC paths on Windows).\n *\n * Note that this _doesn't_ necessarily limit the walk to the\n * `root` directory, and doesn't affect the cwd starting point for\n * non-absolute patterns. A pattern containing `..` will still be\n * able to traverse out of the root directory, if it is not an\n * actual root directory on the filesystem, and any non-absolute\n * patterns will be matched in the `cwd`. For example, the\n * pattern `/../*` with `{root:'/some/path'}` will return all\n * files in `/some`, not all files in `/some/path`. The pattern\n * `*` with `{root:'/some/path'}` will return all the entries in\n * the cwd, not the entries in `/some/path`.\n *\n * To start absolute and non-absolute patterns in the same\n * path, you can use `{root:''}`. However, be aware that on\n * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n * _always_ start in the `x:/` or `//host/share` directory,\n * regardless of the `root` setting.\n */\n root?: string\n\n /**\n * A [PathScurry](http://npm.im/path-scurry) object used\n * to traverse the file system. If the `nocase` option is set\n * explicitly, then any provided `scurry` object must match this\n * setting.\n */\n scurry?: PathScurry\n\n /**\n * Call `lstat()` on all entries, whether required or not to determine\n * if it's a valid match. When used with {@link withFileTypes}, this means\n * that matches will include data such as modified time, permissions, and\n * so on. Note that this will incur a performance cost due to the added\n * system calls.\n */\n stat?: boolean\n\n /**\n * An AbortSignal which will cancel the Glob walk when\n * triggered.\n */\n signal?: AbortSignal\n\n /**\n * Use `\\\\` as a path separator _only_, and\n * _never_ as an escape character. If set, all `\\\\` characters are\n * replaced with `/` in the pattern.\n *\n * Note that this makes it **impossible** to match against paths\n * containing literal glob pattern characters, but allows matching\n * with patterns constructed using `path.join()` and\n * `path.resolve()` on Windows platforms, mimicking the (buggy!)\n * behavior of Glob v7 and before on Windows. Please use with\n * caution, and be mindful of [the caveat below about Windows\n * paths](#windows). (For legacy reasons, this is also set if\n * `allowWindowsEscape` is set to the exact value `false`.)\n */\n windowsPathsNoEscape?: boolean\n\n /**\n * Return [PathScurry](http://npm.im/path-scurry)\n * `Path` objects instead of strings. These are similar to a\n * NodeJS `Dirent` object, but with additional methods and\n * properties.\n *\n * Conflicts with {@link absolute}\n */\n withFileTypes?: boolean\n\n /**\n * An fs implementation to override some or all of the defaults. See\n * http://npm.im/path-scurry for details about what can be overridden.\n */\n fs?: FSOption\n\n /**\n * Return `/` delimited paths, even on Windows.\n *\n * On posix systems, this has no effect. But, on Windows, it means that\n * paths will be `/` delimited, and absolute paths will be their full\n * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n * `'//?/C:/foo/bar'`\n */\n posix?: boolean\n\n /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: boolean\n\n /**\n * max number of `{...}` patterns to expand. Default `1_000`.\n *\n * Note: this is much less than minimatch's default of `100_000`,\n * because Glob has higher memory requirements due to walking\n * the file system tree.\n */\n braceExpandMax?: number\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n withFileTypes: true\n // string options not relevant if returning Path objects.\n absolute?: undefined\n mark?: undefined\n posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n withFileTypes?: undefined\n}\n\nexport type Result =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? false\n : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n absolute?: boolean\n cwd: string\n root?: string\n dot: boolean\n dotRelative: boolean\n follow: boolean\n ignore?: string | string[] | IgnoreLike | ReadonlyArray\n magicalBraces: boolean\n mark?: boolean\n matchBase: boolean\n maxDepth: number\n nobrace: boolean\n nocase: boolean\n nodir: boolean\n noext: boolean\n noglobstar: boolean\n pattern: string[] | ReadonlyArray\n platform: NodeJS.Platform\n realpath: boolean\n scurry: PathScurry\n stat: boolean\n signal?: AbortSignal\n windowsPathsNoEscape: boolean\n withFileTypes: FileTypes\n includeChildMatches: boolean\n\n /**\n * The options provided to the constructor.\n */\n opts: Opts\n\n /**\n * An array of parsed immutable {@link Pattern} objects.\n */\n patterns: Pattern[]\n\n /**\n * All options are stored as properties on the `Glob` object.\n *\n * See {@link GlobOptions} for full options descriptions.\n *\n * Note that a previous `Glob` object can be passed as the\n * `GlobOptions` to another `Glob` instantiation to re-use settings\n * and caches with a new pattern.\n *\n * Traversal functions can be called multiple times to run the walk\n * again.\n */\n constructor(pattern: string | string[], opts: Opts) {\n /* c8 ignore start */\n if (!opts) throw new TypeError('glob options required')\n /* c8 ignore stop */\n this.withFileTypes = !!opts.withFileTypes as FileTypes\n this.signal = opts.signal\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.dotRelative = !!opts.dotRelative\n this.nodir = !!opts.nodir\n this.mark = !!opts.mark\n if (!opts.cwd) {\n this.cwd = ''\n } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n opts.cwd = fileURLToPath(opts.cwd)\n }\n this.cwd = opts.cwd || ''\n this.root = opts.root\n this.magicalBraces = !!opts.magicalBraces\n this.nobrace = !!opts.nobrace\n this.noext = !!opts.noext\n this.realpath = !!opts.realpath\n this.absolute = opts.absolute\n this.includeChildMatches = opts.includeChildMatches !== false\n\n this.noglobstar = !!opts.noglobstar\n this.matchBase = !!opts.matchBase\n this.maxDepth =\n typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n this.stat = !!opts.stat\n this.ignore = opts.ignore\n\n if (this.withFileTypes && this.absolute !== undefined) {\n throw new Error('cannot set absolute and withFileTypes:true')\n }\n\n let p: string[] = typeof pattern === 'string' ? [pattern] : pattern\n\n this.windowsPathsNoEscape =\n !!opts.windowsPathsNoEscape ||\n (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n false\n\n if (this.windowsPathsNoEscape) {\n p = p.map(p => p.replace(/\\\\/g, '/'))\n }\n\n if (this.matchBase) {\n if (opts.noglobstar) {\n throw new TypeError('base matching requires globstar')\n }\n p = p.map(p => (p.includes('/') ? p : `./**/${p}`))\n }\n\n this.pattern = p\n\n this.platform = opts.platform || defaultPlatform\n this.opts = { ...opts, platform: this.platform }\n if (opts.scurry) {\n this.scurry = opts.scurry\n if (\n opts.nocase !== undefined &&\n opts.nocase !== opts.scurry.nocase\n ) {\n throw new Error('nocase option contradicts provided scurry option')\n }\n } else {\n const Scurry =\n opts.platform === 'win32' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? PathScurryPosix\n : PathScurry\n this.scurry = new Scurry(this.cwd, {\n nocase: opts.nocase,\n fs: opts.fs,\n })\n }\n this.nocase = this.scurry.nocase\n\n // If you do nocase:true on a case-sensitive file system, then\n // we need to use regexps instead of strings for non-magic\n // path portions, because statting `aBc` won't return results\n // for the file `AbC` for example.\n const nocaseMagicOnly =\n this.platform === 'darwin' || this.platform === 'win32'\n\n const mmo: MinimatchOptions = {\n braceExpandMax: 10_000,\n ...opts,\n dot: this.dot,\n matchBase: this.matchBase,\n nobrace: this.nobrace,\n // default nocase based on platform\n nocase: this.nocase,\n nocaseMagicOnly,\n nocomment: true,\n noext: this.noext,\n nonegate: true,\n optimizationLevel: 2,\n platform: this.platform,\n windowsPathsNoEscape: this.windowsPathsNoEscape,\n }\n\n const mms = this.pattern.map(p => new Minimatch(p, mmo))\n const [matchSet, globParts] = mms.reduce(\n (set: [MatchSet, GlobParts], m) => {\n set[0].push(...m.set)\n set[1].push(...m.globParts)\n return set\n },\n [[], []],\n )\n this.patterns = matchSet.map((set, i) => {\n const g = globParts[i]\n /* c8 ignore start */\n if (!g) throw new Error('invalid pattern object')\n /* c8 ignore stop */\n return new Pattern(set, g, 0, this.platform)\n })\n }\n\n /**\n * Returns a Promise that resolves to the results array.\n */\n async walk(): Promise>\n async walk(): Promise<(string | Path)[]> {\n // Walkers always return array of Path objects, so we just have to\n // coerce them into the right shape. It will have already called\n // realpath() if the option was set to do so, so we know that's cached.\n // start out knowing the cwd, at least\n return await new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walk()\n }\n\n /**\n * synchronous {@link Glob.walk}\n */\n walkSync(): Results\n walkSync(): (string | Path)[] {\n return new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walkSync()\n }\n\n /**\n * Stream results asynchronously.\n */\n stream(): Minipass, Result>\n stream(): Minipass {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).stream()\n }\n\n /**\n * Stream results synchronously.\n */\n streamSync(): Minipass, Result>\n streamSync(): Minipass {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).streamSync()\n }\n\n /**\n * Default sync iteration function. Returns a Generator that\n * iterates over the results.\n */\n iterateSync(): Generator, void, void> {\n return this.streamSync()[Symbol.iterator]()\n }\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n /**\n * Default async iteration function. Returns an AsyncGenerator that\n * iterates over the results.\n */\n iterate(): AsyncGenerator, void, void> {\n return this.stream()[Symbol.asyncIterator]()\n }\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.d.ts b/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.d.ts index 8aec3bd9725175d9c72be14476fea2a117ca8b09..a152a0985717648c2dc1be586ca2471474b91968 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.d.ts +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.d.ts @@ -1,4 +1,4 @@ -import { GlobOptions } from './glob.js'; +import type { GlobOptions } from './glob.js'; /** * Return true if the patterns provided contain any magic glob characters, * given the options provided. diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.d.ts.map index e2f7e449672a5f671e82090a226ded1ccad56c1d..c916528fa393fc8e3ccb7af4ffffaf96a29084d1 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.d.ts.map +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,GACnB,SAAS,MAAM,GAAG,MAAM,EAAE,EAC1B,UAAS,WAAgB,KACxB,OAQF,CAAA"} \ No newline at end of file +{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAE5C;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,GACnB,SAAS,MAAM,GAAG,MAAM,EAAE,EAC1B,UAAS,WAAgB,KACxB,OAKF,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.js b/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.js index 0918bd57e0f1c2af51957ade7288a1fd75c7e23d..92638089e3cf40b42e9a45077b125d646b96b9b5 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.js +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.js @@ -14,10 +14,7 @@ const minimatch_1 = require("minimatch"); * is in the options, brace expansion _is_ treated as a pattern having magic. */ const hasMagic = (pattern, options = {}) => { - if (!Array.isArray(pattern)) { - pattern = [pattern]; - } - for (const p of pattern) { + for (const p of Array.isArray(pattern) ? pattern : [pattern]) { if (new minimatch_1.Minimatch(p, options).hasMagic()) return true; } diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.js.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.js.map index 44deab290582768bc18722a0f6cf0d4b03312097..c5cbed3458061c5f22bfbe0ba80d1ee68984cac9 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.js.map +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/has-magic.js.map @@ -1 +1 @@ -{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":";;;AAAA,yCAAqC;AAGrC;;;;;;;;;;GAUG;AACI,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,IAAI,qBAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AAXY,QAAA,QAAQ,YAWpB","sourcesContent":["import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n pattern: string | string[],\n options: GlobOptions = {},\n): boolean => {\n if (!Array.isArray(pattern)) {\n pattern = [pattern]\n }\n for (const p of pattern) {\n if (new Minimatch(p, options).hasMagic()) return true\n }\n return false\n}\n"]} \ No newline at end of file +{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":";;;AAAA,yCAAqC;AAGrC;;;;;;;;;;GAUG;AACI,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,KAAK,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7D,IAAI,IAAI,qBAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AARY,QAAA,QAAQ,YAQpB","sourcesContent":["import { Minimatch } from 'minimatch'\nimport type { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n pattern: string | string[],\n options: GlobOptions = {},\n): boolean => {\n for (const p of Array.isArray(pattern) ? pattern : [pattern]) {\n if (new Minimatch(p, options).hasMagic()) return true\n }\n return false\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.d.ts b/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.d.ts index 1893b16df877c9b50c071ee7b066715f6e58c43e..59f0bdbb8fe637b5ba791474140b2ec27b74d52f 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.d.ts +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.d.ts @@ -1,6 +1,7 @@ -import { Minimatch, MinimatchOptions } from 'minimatch'; -import { Path } from 'path-scurry'; -import { GlobWalkerOpts } from './walker.js'; +import type { MinimatchOptions } from 'minimatch'; +import { Minimatch } from 'minimatch'; +import type { Path } from 'path-scurry'; +import type { GlobWalkerOpts } from './walker.js'; export interface IgnoreLike { ignored?: (p: Path) => boolean; childrenIgnored?: (p: Path) => boolean; @@ -16,7 +17,18 @@ export declare class Ignore implements IgnoreLike { absoluteChildren: Minimatch[]; platform: NodeJS.Platform; mmopts: MinimatchOptions; - constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, platform, }: GlobWalkerOpts); + /** + * The escaped glob for the directory that a pattern starting with + * `/` is rooted at, with no trailing `/`. + */ + slashRoot: string; + /** + * Patterns that start with `/` (but not drive letters or UNC paths + * on Windows) start at the `root` option if it is set, or else at + * the root of `cwd`, the same as non-ignored patterns. If `cwd` is + * not provided, they start at `/`. + */ + constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, normalize, platform, root, windowsPathsNoEscape, allowWindowsEscape, braceExpandMax, }: GlobWalkerOpts, cwd?: Path); add(ign: string): void; ignored(p: Path): boolean; childrenIgnored(p: Path): boolean; diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.d.ts.map index 57d6ab6153d770397a5acb7881ccf52a048dee89..7be6090bed2836ff447303b85bc1168bb9afa0e6 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.d.ts.map +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;AACH,qBAAa,MAAO,YAAW,UAAU;IACvC,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;gBAGtB,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAA0B,GAC3B,EAAE,cAAc;IAqBnB,GAAG,CAAC,GAAG,EAAE,MAAM;IAyCf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"} \ No newline at end of file +{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACjD,OAAO,EAAU,SAAS,EAAE,MAAM,WAAW,CAAA;AAC7C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAEvC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEjD,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;AACH,qBAAa,MAAO,YAAW,UAAU;IACvC,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;IACxB;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAA;IAEjB;;;;;OAKG;gBAED,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,SAAS,EACT,QAA0B,EAC1B,IAAI,EACJ,oBAAoB,EACpB,kBAAkB,EAClB,cAAuB,GACxB,EAAE,cAAc,EACjB,GAAG,CAAC,EAAE,IAAI;IA+BZ,GAAG,CAAC,GAAG,EAAE,MAAM;IA6Cf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.js b/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.js index 5f1fde0680dea3736262381efa776c7f8268a70d..50ed77d6779602a6558687879679e2f8a27dbb47 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.js +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.js @@ -22,23 +22,41 @@ class Ignore { absoluteChildren; platform; mmopts; - constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) { + /** + * The escaped glob for the directory that a pattern starting with + * `/` is rooted at, with no trailing `/`. + */ + slashRoot; + /** + * Patterns that start with `/` (but not drive letters or UNC paths + * on Windows) start at the `root` option if it is set, or else at + * the root of `cwd`, the same as non-ignored patterns. If `cwd` is + * not provided, they start at `/`. + */ + constructor(ignored, { nobrace, nocase, noext, noglobstar, normalize, platform = defaultPlatform, root, windowsPathsNoEscape, allowWindowsEscape, braceExpandMax = 10_000, }, cwd) { this.relative = []; this.absolute = []; this.relativeChildren = []; this.absoluteChildren = []; this.platform = platform; + windowsPathsNoEscape = + !!windowsPathsNoEscape || allowWindowsEscape === false; this.mmopts = { + braceExpandMax, dot: true, nobrace, nocase, noext, noglobstar, + normalize, optimizationLevel: 2, platform, nocomment: true, nonegate: true, + windowsPathsNoEscape, }; + const slashRoot = cwd?.resolve(root ?? '/').fullpath() ?? '/'; + this.slashRoot = (0, minimatch_1.escape)(slashRoot.replace(/\\/g, '/').replace(/\/$/, ''), { magicalBraces: true, windowsPathsNoEscape }); for (const ign of ignored) this.add(ign); } @@ -71,7 +89,10 @@ class Ignore { } /* c8 ignore stop */ const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform); - const m = new minimatch_1.Minimatch(p.globString(), this.mmopts); + const glob = p.root() === '/' ? + `${this.slashRoot}/${p.rest()?.globString() ?? ''}` + : p.globString(); + const m = new minimatch_1.Minimatch(glob, this.mmopts); const children = globParts[globParts.length - 1] === '**'; const absolute = p.isAbsolute(); if (absolute) @@ -102,8 +123,8 @@ class Ignore { return false; } childrenIgnored(p) { - const fullpath = p.fullpath() + '/'; - const relative = (p.relative() || '.') + '/'; + const fullpath = `${p.fullpath()}/`; + const relative = `${p.relative() || '.'}/`; for (const m of this.relativeChildren) { if (m.match(relative)) return true; diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.js.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.js.map index d9dfdfa34ab5c0e734952abd3c8070f804efcb1f..c67ca26aa7888c7406f4592d148aa0110c415caa 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.js.map +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/ignore.js.map @@ -1 +1 @@ -{"version":3,"file":"ignore.js","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,kCAAkC;AAClC,kEAAkE;AAClE,6CAA6C;;;AAE7C,yCAAuD;AAEvD,6CAAsC;AAStC,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAEX;;GAEG;AACH,MAAa,MAAM;IACjB,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAiB;IACzB,MAAM,CAAkB;IAExB,YACE,OAAiB,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAAQ,GAAG,eAAe,GACX;QAEjB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,MAAM,GAAG;YACZ,GAAG,EAAE,I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AI,CAAA;QAC1D,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,eAAe,CAAC,CAAO;QACrB,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,GAAG,CAAA;QACnC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,GAAG,GAAG,CAAA;QAC5C,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAvGD,wBAuGC","sourcesContent":["// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n ignored?: (p: Path) => boolean\n childrenIgnored?: (p: Path) => boolean\n add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n relative: Minimatch[]\n relativeChildren: Minimatch[]\n absolute: Minimatch[]\n absoluteChildren: Minimatch[]\n platform: NodeJS.Platform\n mmopts: MinimatchOptions\n\n constructor(\n ignored: string[],\n {\n nobrace,\n nocase,\n noext,\n noglobstar,\n platform = defaultPlatform,\n }: GlobWalkerOpts,\n ) {\n this.relative = []\n this.absolute = []\n this.relativeChildren = []\n this.absoluteChildren = []\n this.platform = platform\n this.mmopts = {\n dot: true,\n nobrace,\n nocase,\n noext,\n noglobstar,\n optimizationLevel: 2,\n platform,\n nocomment: true,\n nonegate: true,\n }\n for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\n // this is a little weird, but it gives us a clean set of optimized\n // minimatch matchers, without getting tripped up if one of them\n // ends in /** inside a brace section, and it's only inefficient at\n // the start of the walk, not along it.\n // It'd be nice if the Pattern class just had a .test() method, but\n // handling globstars is a bit of a pita, and that code already lives\n // in minimatch anyway.\n // Another way would be if maybe Minimatch could take its set/globParts\n // as an option, and then we could at least just use Pattern to test\n // for absolute-ness.\n // Yet another way, Minimatch could take an array of glob strings, and\n // a cwd option, and do the right thing.\n const mm = new Minimatch(ign, this.mmopts)\n for (let i = 0; i < mm.set.length; i++) {\n const parsed = mm.set[i]\n const globParts = mm.globParts[i]\n /* c8 ignore start */\n if (!parsed || !globParts) {\n throw new Error('invalid pattern object')\n }\n // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.mmopts)\n const children = globParts[globParts.length - 1] === '**'\n const absolute = p.isAbsolute()\n if (absolute) this.absolute.push(m)\n else this.relative.push(m)\n if (children) {\n if (absolute) this.absoluteChildren.push(m)\n else this.relativeChildren.push(m)\n }\n }\n }\n\n ignored(p: Path): boolean {\n const fullpath = p.fullpath()\n const fullpaths = `${fullpath}/`\n const relative = p.relative() || '.'\n const relatives = `${relative}/`\n for (const m of this.relative) {\n if (m.match(relative) || m.match(relatives)) return true\n }\n for (const m of this.absolute) {\n if (m.match(fullpath) || m.match(fullpaths)) return true\n }\n return false\n }\n\n childrenIgnored(p: Path): boolean {\n const fullpath = p.fullpath() + '/'\n const relative = (p.relative() || '.') + '/'\n for (const m of this.relativeChildren) {\n if (m.match(relative)) return true\n }\n for (const m of this.absoluteChildren) {\n if (m.match(fullpath)) return true\n }\n return false\n }\n}\n"]} \ No newline at end of file +{"version":3,"file":"ignore.js","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,kCAAkC;AAClC,kEAAkE;AAClE,6CAA6C;;;AAG7C,yCAA6C;AAE7C,6CAAsC;AAStC,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAEX;;GAEG;AACH,MAAa,MAAM;IACjB,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAiB;IACzB,MAAM,CAAkB;IACxB;;;OAGG;IACH,SAAS,CAAQ;IAEjB;;;;;OAKG;IACH,YACE,OAAiB,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,SAAS,EACT,QAAQ,GAAG,eAAe,EAC1B,IAAI,EACJ,oBAAoB,EACpB,kBAAkB,EAClB,cAAc,GAAG,MAAM,GACR,EACjB,GAAU;QAEV,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,oBAAoB;YAClB,CAAC,CAAC,oBAAoB,IAAI,kBAAkB,KAAK,KAAK,CAAA;QACxD,IAAI,CAAC,MAAM,GAAG;YACZ,cAAc;YACd,GAAG,EAAE,IAAI;YACT,OAAO;YACP,MAAM;YACN,KA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,GAAG,QAAQ,GAAG,CAAA;QAChC,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAA;QACpC,MAAM,SAAS,GAAG,GAAG,QAAQ,GAAG,CAAA;QAChC,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,eAAe,CAAC,CAAO;QACrB,MAAM,QAAQ,GAAG,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,CAAA;QACnC,MAAM,QAAQ,GAAG,GAAG,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,GAAG,CAAA;QAC1C,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAtID,wBAsIC","sourcesContent":["// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport type { MinimatchOptions } from 'minimatch'\nimport { escape, Minimatch } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport type { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n ignored?: (p: Path) => boolean\n childrenIgnored?: (p: Path) => boolean\n add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n relative: Minimatch[]\n relativeChildren: Minimatch[]\n absolute: Minimatch[]\n absoluteChildren: Minimatch[]\n platform: NodeJS.Platform\n mmopts: MinimatchOptions\n /**\n * The escaped glob for the directory that a pattern starting with\n * `/` is rooted at, with no trailing `/`.\n */\n slashRoot: string\n\n /**\n * Patterns that start with `/` (but not drive letters or UNC paths\n * on Windows) start at the `root` option if it is set, or else at\n * the root of `cwd`, the same as non-ignored patterns. If `cwd` is\n * not provided, they start at `/`.\n */\n constructor(\n ignored: string[],\n {\n nobrace,\n nocase,\n noext,\n noglobstar,\n normalize,\n platform = defaultPlatform,\n root,\n windowsPathsNoEscape,\n allowWindowsEscape,\n braceExpandMax = 10_000,\n }: GlobWalkerOpts,\n cwd?: Path,\n ) {\n this.relative = []\n this.absolute = []\n this.relativeChildren = []\n this.absoluteChildren = []\n this.platform = platform\n windowsPathsNoEscape =\n !!windowsPathsNoEscape || allowWindowsEscape === false\n this.mmopts = {\n braceExpandMax,\n dot: true,\n nobrace,\n nocase,\n noext,\n noglobstar,\n normalize,\n optimizationLevel: 2,\n platform,\n nocomment: true,\n nonegate: true,\n windowsPathsNoEscape,\n }\n const slashRoot = cwd?.resolve(root ?? '/').fullpath() ?? '/'\n this.slashRoot = escape(\n slashRoot.replace(/\\\\/g, '/').replace(/\\/$/, ''),\n { magicalBraces: true, windowsPathsNoEscape },\n )\n for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\n // this is a little weird, but it gives us a clean set of optimized\n // minimatch matchers, without getting tripped up if one of them\n // ends in /** inside a brace section, and it's only inefficient at\n // the start of the walk, not along it.\n // It'd be nice if the Pattern class just had a .test() method, but\n // handling globstars is a bit of a pita, and that code already lives\n // in minimatch anyway.\n // Another way would be if maybe Minimatch could take its set/globParts\n // as an option, and then we could at least just use Pattern to test\n // for absolute-ness.\n // Yet another way, Minimatch could take an array of glob strings, and\n // a cwd option, and do the right thing.\n const mm = new Minimatch(ign, this.mmopts)\n for (let i = 0; i < mm.set.length; i++) {\n const parsed = mm.set[i]\n const globParts = mm.globParts[i]\n /* c8 ignore start */\n if (!parsed || !globParts) {\n throw new Error('invalid pattern object')\n }\n // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const glob =\n p.root() === '/' ?\n `${this.slashRoot}/${p.rest()?.globString() ?? ''}`\n : p.globString()\n const m = new Minimatch(glob, this.mmopts)\n const children = globParts[globParts.length - 1] === '**'\n const absolute = p.isAbsolute()\n if (absolute) this.absolute.push(m)\n else this.relative.push(m)\n if (children) {\n if (absolute) this.absoluteChildren.push(m)\n else this.relativeChildren.push(m)\n }\n }\n }\n\n ignored(p: Path): boolean {\n const fullpath = p.fullpath()\n const fullpaths = `${fullpath}/`\n const relative = p.relative() || '.'\n const relatives = `${relative}/`\n for (const m of this.relative) {\n if (m.match(relative) || m.match(relatives)) return true\n }\n for (const m of this.absolute) {\n if (m.match(fullpath) || m.match(fullpaths)) return true\n }\n return false\n }\n\n childrenIgnored(p: Path): boolean {\n const fullpath = `${p.fullpath()}/`\n const relative = `${p.relative() || '.'}/`\n for (const m of this.relativeChildren) {\n if (m.match(relative)) return true\n }\n for (const m of this.absoluteChildren) {\n if (m.match(fullpath)) return true\n }\n return false\n }\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.d.ts b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.d.ts index cb09bfb64acb34985b08e658882181a3fff9bd38..05abf240752bdc2256ccbb79efc4cca3694c4750 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.d.ts +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.d.ts @@ -1,8 +1,9 @@ -import { Minipass } from 'minipass'; -import { Path } from 'path-scurry'; +import type { Minipass } from 'minipass'; +import type { Path } from 'path-scurry'; import type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset } from './glob.js'; import { Glob } from './glob.js'; export { escape, unescape } from 'minimatch'; +export type { Form } from 'minimatch'; export type { FSOption, Path, WalkOptions, WalkOptionsWithFileTypesTrue, WalkOptionsWithFileTypesUnset, } from 'path-scurry'; export { Glob } from './glob.js'; export type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset, } from './glob.js'; diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.d.ts.map index 5fb32252b63747526a971d82bf6ab2ee61b53631..f505cef301541868c7ca11eb5f2a8bfbdbe8fa4e 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.d.ts.map +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,KAAK,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,EAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAGhC,OAAO,EAAE,MAAM,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A4B,GACpC,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACnC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACrC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AASxE,eAAO,MAAM,UAAU,uBAAiB,CAAA;AACxC,eAAO,MAAM,MAAM;;CAAsD,CAAA;AACzE,eAAO,MAAM,WAAW,wBAAkB,CAAA;AAC1C,eAAO,MAAM,OAAO;;CAElB,CAAA;AACF,eAAO,MAAM,IAAI;;;CAGf,CAAA;AAEF,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;CAgBf,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.js.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.js.map index e648b1d01939bc921393d446606768c86edfba71..8104d8f55fc3d4fb2a35ebdec99fce7d85255ec9 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.js.map +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAqDA,wCAKC;AAsBD,gCAKC;AAqBD,4BAKC;AAkDD,0CAKC;AAqBD,kCAKC;AAhMD,yCAA4C;AAS5C,uCAAgC;AAChC,iDAAyC;AAEzC,uCAA4C;AAAnC,mGAAA,MAAM,OAAA;AAAE,qGAAA,QAAQ,OAAA;AAQzB,qCAAgC;AAAvB,+FAAA,IAAI,OAAA;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I,EAAE,eAAe;CACtB,CAAC,CAAA;AACW,QAAA,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC1C,MAAM,EAAE,cAAc;IACtB,OAAO,EAAE,eAAe;CACzB,CAAC,CAAA;AAEW,QAAA,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,KAAK;IACX,QAAQ;IACR,IAAI,EAAJ,YAAI;IACJ,UAAU;IACV,MAAM,EAAN,cAAM;IACN,cAAc;IACd,UAAU,EAAV,kBAAU;IACV,WAAW;IACX,OAAO,EAAP,eAAO;IACP,eAAe;IACf,WAAW,EAAX,mBAAW;IACX,IAAI,EAAJ,cAAI;IACJ,QAAQ,EAAR,uBAAQ;IACR,MAAM,EAAN,kBAAM;IACN,QAAQ,EAAR,oBAAQ;CACT,CAAC,CAAA;AACF,YAAI,CAAC,IAAI,GAAG,YAAI,CAAA","sourcesContent":["import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n stream: globStreamSync,\n iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n glob: glob_,\n globSync,\n sync,\n globStream,\n stream,\n globStreamSync,\n streamSync,\n globIterate,\n iterate,\n globIterateSync,\n iterateSync,\n Glob,\n hasMagic,\n escape,\n unescape,\n})\nglob.glob = glob\n"]} \ No newline at end of file +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAsDA,wCAKC;AAsBD,gCAKC;AAqBD,4BAKC;AAkDD,0CAKC;AAqBD,kCAKC;AAjMD,yCAA4C;AAS5C,uCAAgC;AAChC,iDAAyC;AAEzC,uCAA4C;AAAnC,mGAAA,MAAM,OAAA;AAAE,qGAAA,QAAQ,OAAA;AASzB,qCAAgC;AAAvB,+FAAA,IAAI,OAAA;AAOb,+CAAyC;AAAhC,wGAAA,QAAQ,OAAA;AACjB,yCAAoC;AAA3B,mGAAA,MAAM,OAAA;AAyBf,SAAgB,cAAc,CAC5B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAA;AAChD,CAAC;AAsBD,SAAgB,UAAU,CACxB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,EAAE,CAAA;AAC5C,CAAC;AAqBD,SAAgB,QAAQ,CACtB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAA;AAC9C,CAAC;AAwBD,KAAK,UAAU,KAAK,CAClB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAA;AAC1C,CAAC;AAqBD,SAAgB,eAAe,CAC7B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAA;AACjD,CAAC;AAqBD,SAAgB,WAAW,CACzB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,OAAO,EAAE,CAAA;AAC7C,CAAC;AAED,iEAAiE;AACpD,QAAA,UAAU,GAAG,cAAc,CAAA;AAC3B,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAA;AAC5D,QAAA,WAAW,GAAG,eAAe,CAAA;AAC7B,QAAA,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;IAChD,IAAI,EAAE,eAAe;CACtB,CAAC,CAAA;AACW,QAAA,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC1C,MAAM,EAAE,cAAc;IACtB,OAAO,EAAE,eAAe;CACzB,CAAC,CAAA;AAEW,QAAA,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,KAAK;IACX,QAAQ;IACR,IAAI,EAAJ,YAAI;IACJ,UAAU;IACV,MAAM,EAAN,cAAM;IACN,cAAc;IACd,UAAU,EAAV,kBAAU;IACV,WAAW;IACX,OAAO,EAAP,eAAO;IACP,eAAe;IACf,WAAW,EAAX,mBAAW;IACX,IAAI,EAAJ,cAAI;IACJ,QAAQ,EAAR,uBAAQ;IACR,MAAM,EAAN,kBAAM;IACN,QAAQ,EAAR,oBAAQ;CACT,CAAC,CAAA;AACF,YAAI,CAAC,IAAI,GAAG,YAAI,CAAA","sourcesContent":["import { escape, unescape } from 'minimatch'\nimport type { Minipass } from 'minipass'\nimport type { Path } from 'path-scurry'\nimport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type { Form } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions,\n): Promise\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n stream: globStreamSync,\n iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n glob: glob_,\n globSync,\n sync,\n globStream,\n stream,\n globStreamSync,\n streamSync,\n globIterate,\n iterate,\n globIterateSync,\n iterateSync,\n Glob,\n hasMagic,\n escape,\n unescape,\n})\nglob.glob = glob\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.min.js b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.min.js index 4828ba07860bdc8ecee7a976f1e7299164b0057e..df030d445f520acb4b4ed090455f5bb8ec730cb0 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.min.js +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.min.js @@ -1,4 +1,3 @@ -"use strict";var R=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Ge=R(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.range=Y.balanced=void 0;var Gs=(n,t,e)=>{let s=n instanceof RegExp?Ie(n,e):n,i=t instanceof RegExp?Ie(t,e):t,r=s!==null&&i!=null&&(0,Y.range)(s,i,e);return r&&{start:r[0],end:r[1],pre:e.slice(0,r[0]),body:e.slice(r[0]+s.length,r[1]),post:e.slice(r[1]+i.length)}};Y.balanced=Gs;var Ie=(n,t)=>{let e=t.match(n);return e?e[0]:null},zs=(n,t,e)=>{let s,i,r,h,o,a=e.indexOf(n),l=e.indexOf(t,a+1),f=a;if(a>=0&&l>0){if(n===t)return[a,l];for(s=[],r=e.length;f>=0&&!o;){if(f===a)s.push(f),a=e.indexOf(n,f+1);else if(s.length===1){let c=s.pop();c!==void 0&&(o=[c,l])}else i=s.pop(),i!==void 0&&i=0?a:l}s.length&&h!==void 0&&(o=[r,h])}return o};Y.range=zs});var Ke=R(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.EXPANSION_MAX=void 0;it.expand=ei;var ze=Ge(),Ue="\0SLASH"+Math.random()+"\0",$e="\0OPEN"+Math.random()+"\0",ue="\0CLOSE"+Math.random()+"\0",qe="\0COMMA"+Math.random()+"\0",He="\0PERIOD"+Math.random()+"\0",Us=new RegExp(Ue,"g"),$s=new RegExp($e,"g"),qs=new RegExp(ue,"g"),Hs=new RegExp(qe,"g"),Vs=new RegExp(He,"g"),Ks=/\\\\/g,Xs=/\\{/g,Ys=/\\}/g,Js=/\\,/g,Zs=/\\./g;it.EXPANSION_MAX=1e5;function ce(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function Qs(n){return n.replace(Ks,Ue).replace(Xs,$e).replace(Ys,ue).replace(Js,qe).replace(Zs,He)}function ti(n){return n.replace(Us,"\\").replace($s,"{").replace(qs,"}").replace(Hs,",").replace(Vs,".")}function Ve(n){if(!n)return[""];let t=[],e=(0,ze.balanced)("{","}",n);if(!e)return n.split(",");let{pre:s,body:i,post:r}=e,h=s.split(",");h[h.length-1]+="{"+i+"}";let o=Ve(r);return r.length&&(h[h.length-1]+=o.shift(),h.push.apply(h,o)),t.push.apply(t,h),t}function ei(n,t={}){if(!n)return[];let{max:e=it.EXPANSION_MAX}=t;return n.slice(0,2)==="{}"&&(n="\\{\\}"+n.slice(2)),ht(Qs(n),e,!0).map(ti)}function si(n){return"{"+n+"}"}function ii(n){return/^-?0\d/.test(n)}function ri(n,t){return n<=t}function ni(n,t){return n>=t}function ht(n,t,e){let s=[],i=(0,ze.balanced)("{","}",n);if(!i)return[n];let r=i.pre,h=i.post.length?ht(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let o=0;o=0;if(!l&&!f)return i.post.match(/,(?!,).*\}/)?(n=i.pre+"{"+i.body+ue+i.post,ht(n,t,!0)):[n];let c;if(l)c=i.body.split(/\.\./);else if(c=Ve(i.body),c.length===1&&c[0]!==void 0&&(c=ht(c[0],t,!1).map(si),c.length===1))return h.map(u=>i.pre+c[0]+u);let d;if(l&&c[0]!==void 0&&c[1]!==void 0){let u=ce(c[0]),m=ce(c[1]),p=Math.max(c[0].length,c[1].length),b=c.length===3&&c[2]!==void 0?Math.abs(ce(c[2])):1,w=ri;m0){let U=new Array(B+1).join("0");y<0?S="-"+U+S.slice(1):S=U+S}}d.push(S)}}else{d=[];for(let u=0;u{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.assertValidPattern=void 0;var hi=1024*64,oi=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>hi)throw new TypeError("pattern is too long")};Ct.assertValidPattern=oi});var Je=R(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.parseClass=void 0;var ai={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},ot=n=>n.replace(/[[\]\\-]/g,"\\$&"),li=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ye=n=>n.join(""),ci=(n,t)=>{let e=t;if(n.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],i=[],r=e+1,h=!1,o=!1,a=!1,l=!1,f=e,c="";t:for(;rc?s.push(ot(c)+"-"+ot(p)):p===c&&s.push(ot(p)),c="",r++;continue}if(n.startsWith("-]",r+1)){s.push(ot(p+"-")),r+=2;continue}if(n.startsWith("-",r+1)){c=p,r+=2;continue}s.push(ot(p)),r++}if(f{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.unescape=void 0;var ui=(n,{windowsPathsNoEscape:t=!1,magicalBraces:e=!0}={})=>e?t?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?n.replace(/\[([^\/\\{}])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");At.unescape=ui});var pe=R(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.AST=void 0;var fi=Je(),Mt=kt(),di=new Set(["!","?","+","*","@"]),Ze=n=>di.has(n),pi="(?!(?:^|/)\\.\\.?(?:$|/))",Pt="(?!\\.)",mi=new Set(["[","."]),gi=new Set(["..","."]),wi=new Set("().*{}+?[]^$\\!"),bi=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),de="[^/]",Qe=de+"*?",ts=de+"+?",fe=class n{type;#t;#s;#n=!1;#r=[];#h;#S;#w;#c=!1;#o;#f;#u=!1;constructor(t,e,s={}){this.type=t,t&&(this.#s=!0),this.#h=e,this.#t=this.#h?this.#h.#t:this,this.#o=this.#t===this?s:this.#t.#o,this.#w=this.#t===this?[]:this.#t.#w,t==="!"&&!this.#t.#c&&this.#w.push(this),this.#S=this.#h?this.#h.#r.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#f!==void 0?this.#f:this.type?this.#f=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#f=this.#r.map(t=>String(t)).join("")}#a(){if(this!==this.#t)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let t;for(;t=this.#w.pop();){if(t.type!=="!")continue;let e=t,s=e.#h;for(;s;){for(let i=e.#S+1;!s.type&&itypeof e=="string"?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#c&&this.#h?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#h?.isStart())return!1;if(this.#S===0)return!0;let t=this.#h;for(let e=0;etypeof u!="string"),l=this.#r.map(u=>{let[m,p,b,w]=typeof u=="string"?n.#v(u,this.#s,a):u.toRegExpSource(t);return this.#s=this.#s||b,this.#n=this.#n||w,m}).join(""),f="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&gi.has(this.#r[0]))){let m=mi,p=e&&m.has(l.charAt(0))||l.startsWith("\\.")&&m.has(l.charAt(2))||l.startsWith("\\.\\.")&&m.has(l.charAt(4)),b=!e&&!t&&m.has(l.charAt(0));f=p?pi:b?Pt:""}let c="";return this.isEnd()&&this.#t.#c&&this.#h?.type==="!"&&(c="(?:$|\\/)"),[f+l+c,(0,Mt.unescape)(l),this.#s=!!this.#s,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#d(e);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let a=this.toString();return this.#r=[a],this.type=null,this.#s=void 0,[a,(0,Mt.unescape)(this.toString()),!1,!1]}let h=!s||t||e||!Pt?"":this.#d(!0);h===r&&(h=""),h&&(r=`(?:${r})(?:${h})*?`);let o="";if(this.type==="!"&&this.#u)o=(this.isStart()&&!e?Pt:"")+ts;else{let a=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Pt:"")+Qe+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&h?")":this.type==="*"&&h?")?":`)${this.type}`;o=i+r+a}return[o,(0,Mt.unescape)(r),this.#s=!!this.#s,this.#n]}#d(t){return this.#r.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,i,r,h]=e.toRegExpSource(t);return this.#n=this.#n||h,s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#v(t,e,s=!1){let i=!1,r="",h=!1,o=!1;for(let a=0;a{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.escape=void 0;var yi=(n,{windowsPathsNoEscape:t=!1,magicalBraces:e=!1}={})=>e?t?n.replace(/[?*()[\]{}]/g,"[$&]"):n.replace(/[?*()[\]\\{}]/g,"\\$&"):t?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");Ft.escape=yi});var H=R(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.unescape=g.escape=g.AST=g.Minimatch=g.match=g.makeRe=g.braceExpand=g.defaults=g.filter=g.GLOBSTAR=g.sep=g.minimatch=void 0;var Si=Ke(),jt=Xe(),is=pe(),vi=me(),Ei=kt(),_i=(n,t,e={})=>((0,jt.assertValidPattern)(t),!e.nocomment&&t.charAt(0)==="#"?!1:new J(t,e).match(n));g.minimatch=_i;var Oi=/^\*+([^+@!?\*\[\(]*)$/,xi=n=>t=>!t.startsWith(".")&&t.endsWith(n),Ti=n=>t=>t.endsWith(n),Ci=n=>(n=n.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(n)),Ri=n=>(n=n.toLowerCase(),t=>t.toLowerCase().endsWith(n)),Ai=/^\*+\.\*+$/,ki=n=>!n.startsWith(".")&&n.includes("."),Mi=n=>n!=="."&&n!==".."&&n.includes("."),Pi=/^\.\*+$/,Di=n=>n!=="."&&n!==".."&&n.startsWith("."),Fi=/^\*+$/,ji=n=>n.length!==0&&!n.startsWith("."),Ni=n=>n.length!==0&&n!=="."&&n!=="..",Li=/^\?+([^+@!?\*\[\(]*)?$/,Wi=([n,t=""])=>{let e=rs([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Bi=([n,t=""])=>{let e=ns([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Ii=([n,t=""])=>{let e=ns([n]);return t?s=>e(s)&&s.endsWith(t):e},Gi=([n,t=""])=>{let e=rs([n]);return t?s=>e(s)&&s.endsWith(t):e},rs=([n])=>{let t=n.length;return e=>e.length===t&&!e.startsWith(".")},ns=([n])=>{let t=n.length;return e=>e.length===t&&e!=="."&&e!==".."},hs=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",es={win32:{sep:"\\"},posix:{sep:"/"}};g.sep=hs==="win32"?es.win32.sep:es.posix.sep;g.minimatch.sep=g.sep;g.GLOBSTAR=Symbol("globstar **");g.minimatch.GLOBSTAR=g.GLOBSTAR;var zi="[^/]",Ui=zi+"*?",$i="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",qi="(?:(?!(?:\\/|^)\\.).)*?",Hi=(n,t={})=>e=>(0,g.minimatch)(e,n,t);g.filter=Hi;g.minimatch.filter=g.filter;var F=(n,t={})=>Object.assign({},n,t),Vi=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return g.minimatch;let t=g.minimatch;return Object.assign((s,i,r={})=>t(s,i,F(n,r)),{Minimatch:class extends t.Minimatch{constructor(i,r={}){super(i,F(n,r))}static defaults(i){return t.defaults(F(n,i)).Minimatch}},AST:class extends t.AST{constructor(i,r,h={}){super(i,r,F(n,h))}static fromGlob(i,r={}){return t.AST.fromGlob(i,F(n,r))}},unescape:(s,i={})=>t.unescape(s,F(n,i)),escape:(s,i={})=>t.escape(s,F(n,i)),filter:(s,i={})=>t.filter(s,F(n,i)),defaults:s=>t.defaults(F(n,s)),makeRe:(s,i={})=>t.makeRe(s,F(n,i)),braceExpand:(s,i={})=>t.braceExpand(s,F(n,i)),match:(s,i,r={})=>t.match(s,i,F(n,r)),sep:t.sep,GLOBSTAR:g.GLOBSTAR})};g.defaults=Vi;g.minimatch.defaults=g.defaults;var Ki=(n,t={})=>((0,jt.assertValidPattern)(n),t.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,Si.expand)(n,{max:t.braceExpandMax}));g.braceExpand=Ki;g.minimatch.braceExpand=g.braceExpand;var Xi=(n,t={})=>new J(n,t).makeRe();g.makeRe=Xi;g.minimatch.makeRe=g.makeRe;var Yi=(n,t,e={})=>{let s=new J(t,e);return n=n.filter(i=>s.match(i)),s.options.nonull&&!n.length&&n.push(t),n};g.match=Yi;g.minimatch.match=g.match;var ss=/[?*]|[+@!]\(.*?\)|\[|\]/,Ji=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),J=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){(0,jt.assertValidPattern)(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||hs,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,h,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=r[0]===""&&r[1]===""&&(r[2]==="?"||!ss.test(r[2]))&&!ss.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(a)return[...r.slice(0,4),...r.slice(4).map(f=>this.parse(f))];if(l)return[r[0],...r.slice(1).map(f=>this.parse(f))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,i)=>{let r=s[s.length-1];return i==="**"&&r==="**"?s:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(s.pop(),s):(s.push(i),s)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&s.splice(i+1,h-i);let o=s[i+1],a=s[i+2],l=s[i+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(i,1);let f=s.slice(0);f[i]="**",t.push(f),i--}if(!this.preserveMultipleSlashes){for(let h=1;he.length)}partsMatch(t,e,s=!1){let i=0,r=0,h=[],o="";for(;iE?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:r=1}=this.options;r>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var h=0,o=0,a=t.length,l=e.length;h>> no match, partial?`,t,d,e,u),d===a))}let p;if(typeof f=="string"?(p=c===f,this.debug("string match",f,c,p)):(p=f.test(c),this.debug("pattern match",f,c,p)),!p)return!1}if(h===a&&o===l)return!0;if(h===a)return s;if(o===l)return h===a-1&&t[h]==="";throw new Error("wtf?")}braceExpand(){return(0,g.braceExpand)(this.pattern,this.options)}parse(t){(0,jt.assertValidPattern)(t);let e=this.options;if(t==="**")return g.GLOBSTAR;if(t==="")return"";let s,i=null;(s=t.match(Fi))?i=e.dot?Ni:ji:(s=t.match(Oi))?i=(e.nocase?e.dot?Ri:Ci:e.dot?Ti:xi)(s[1]):(s=t.match(Li))?i=(e.nocase?e.dot?Bi:Wi:e.dot?Ii:Gi)(s):(s=t.match(Ai))?i=e.dot?Mi:ki:(s=t.match(Pi))&&(i=Di);let r=is.AST.fromGlob(t,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,s=e.noglobstar?Ui:e.dot?$i:qi,i=new Set(e.nocase?["i"]:[]),r=t.map(a=>{let l=a.map(c=>{if(c instanceof RegExp)for(let d of c.flags.split(""))i.add(d);return typeof c=="string"?Ji(c):c===g.GLOBSTAR?g.GLOBSTAR:c._src});l.forEach((c,d)=>{let u=l[d+1],m=l[d-1];c!==g.GLOBSTAR||m===g.GLOBSTAR||(m===void 0?u!==void 0&&u!==g.GLOBSTAR?l[d+1]="(?:\\/|"+s+"\\/)?"+u:l[d]=s:u===void 0?l[d-1]=m+"(?:\\/|\\/"+s+")?":u!==g.GLOBSTAR&&(l[d-1]=m+"(?:\\/|\\/"+s+"\\/)"+u,l[d+1]=g.GLOBSTAR))});let f=l.filter(c=>c!==g.GLOBSTAR);if(this.partial&&f.length>=1){let c=[];for(let d=1;d<=f.length;d++)c.push(f.slice(0,d).join("/"));return"(?:"+c.join("|")+")"}return f.join("/")}).join("|"),[h,o]=t.length>1?["(?:",")"]:["",""];r="^"+h+r+o+"$",this.partial&&(r="^(?:\\/|"+h+r.slice(1,-1)+o+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let s=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let r=this.set;this.debug(this.pattern,"set",r);let h=i[i.length-1];if(!h)for(let o=i.length-2;!h&&o>=0;o--)h=i[o];for(let o=0;o{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.LRUCache=void 0;var er=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,as=new Set,ge=typeof process=="object"&&process?process:{},ls=(n,t,e,s)=>{typeof ge.emitWarning=="function"?ge.emitWarning(n,t,e,s):console.error(`[${e}] ${t}: ${n}`)},Lt=globalThis.AbortController,os=globalThis.AbortSignal;if(typeof Lt>"u"){os=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,s){this._onabort.push(s)}},Lt=class{constructor(){t()}signal=new os;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let s of this.signal._onabort)s(e);this.signal.onabort?.(e)}}};let n=ge.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{n&&(n=!1,ls("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var sr=n=>!as.has(n),V=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),cs=n=>V(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Nt:null:null,Nt=class extends Array{constructor(n){super(n),this.fill(0)}},ir=class at{heap;length;static#t=!1;static create(t){let e=cs(t);if(!e)return[];at.#t=!0;let s=new at(t,e);return at.#t=!1,s}constructor(t,e){if(!at.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},rr=class us{#t;#s;#n;#r;#h;#S;#w;#c;get perf(){return this.#c}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#f;#u;#a;#i;#d;#v;#y;#p;#R;#m;#O;#x;#g;#b;#E;#T;#e;#F;static unsafeExposeInternals(t){return{starts:t.#x,ttls:t.#g,autopurgeTimers:t.#b,sizes:t.#O,keyMap:t.#u,keyList:t.#a,valList:t.#i,next:t.#d,prev:t.#v,get head(){return t.#y},get tail(){return t.#p},free:t.#R,isBackgroundFetch:e=>t.#l(e),backgroundFetch:(e,s,i,r)=>t.#z(e,s,i,r),moveToTail:e=>t.#N(e),indexes:e=>t.#k(e),rindexes:e=>t.#M(e),isStale:e=>t.#_(e)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#f}get size(){return this.#o}get fetchMethod(){return this.#S}get memoMethod(){return this.#w}get dispose(){return this.#n}get onInsert(){return this.#r}get disposeAfter(){return this.#h}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:r,updateAgeOnGet:h,updateAgeOnHas:o,allowStale:a,dispose:l,onInsert:f,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:u,maxSize:m=0,maxEntrySize:p=0,sizeCalculation:b,fetchMethod:w,memoMethod:v,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:S,allowStaleOnFetchAbort:B,ignoreFetchAbort:U,perf:et}=t;if(et!==void 0&&typeof et?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#c=et??er,e!==0&&!V(e))throw new TypeError("max option must be a nonnegative integer");let st=e?cs(e):Array;if(!st)throw new Error("invalid max value: "+e);if(this.#t=e,this.#s=m,this.maxEntrySize=p||this.#s,this.sizeCalculation=b,this.sizeCalculation){if(!this.#s&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(v!==void 0&&typeof v!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=v,w!==void 0&&typeof w!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#S=w,this.#T=!!w,this.#u=new Map,this.#a=new Array(e).fill(void 0),this.#i=new Array(e).fill(void 0),this.#d=new st(e),this.#v=new st(e),this.#y=0,this.#p=0,this.#R=ir.create(e),this.#o=0,this.#f=0,typeof l=="function"&&(this.#n=l),typeof f=="function"&&(this.#r=f),typeof c=="function"?(this.#h=c,this.#m=[]):(this.#h=void 0,this.#m=void 0),this.#E=!!this.#n,this.#F=!!this.#r,this.#e=!!this.#h,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!S,this.allowStaleOnFetchAbort=!!B,this.ignoreFetchAbort=!!U,this.maxEntrySize!==0){if(this.#s!==0&&!V(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!V(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!o,this.ttlResolution=V(i)||i===0?i:1,this.ttlAutopurge=!!r,this.ttl=s||0,this.ttl){if(!V(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let le="LRU_CACHE_UNBOUNDED";sr(le)&&(as.add(le),ls("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",le,us))}}getRemainingTTL(t){return this.#u.has(t)?1/0:0}#P(){let t=new Nt(this.#t),e=new Nt(this.#t);this.#g=t,this.#x=e;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#b=s,this.#W=(h,o,a=this.#c.now())=>{if(e[h]=o!==0?a:0,t[h]=o,s?.[h]&&(clearTimeout(s[h]),s[h]=void 0),o!==0&&s){let l=setTimeout(()=>{this.#_(h)&&this.#A(this.#a[h],"expire")},o+1);l.unref&&l.unref(),s[h]=l}},this.#C=h=>{e[h]=t[h]!==0?this.#c.now():0},this.#D=(h,o)=>{if(t[o]){let a=t[o],l=e[o];if(!a||!l)return;h.ttl=a,h.start=l,h.now=i||r();let f=h.now-l;h.remainingTTL=a-f}};let i=0,r=()=>{let h=this.#c.now();if(this.ttlResolution>0){i=h;let o=setTimeout(()=>i=0,this.ttlResolution);o.unref&&o.unref()}return h};this.getRemainingTTL=h=>{let o=this.#u.get(h);if(o===void 0)return 0;let a=t[o],l=e[o];if(!a||!l)return 1/0;let f=(i||r())-l;return a-f},this.#_=h=>{let o=e[h],a=t[h];return!!a&&!!o&&(i||r())-o>a}}#C=()=>{};#D=()=>{};#W=()=>{};#_=()=>!1;#$(){let t=new Nt(this.#t);this.#f=0,this.#O=t,this.#L=e=>{this.#f-=t[e],t[e]=0},this.#B=(e,s,i,r)=>{if(this.#l(s))return 0;if(!V(i))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(i=r(s,e),!V(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#j=(e,s,i)=>{if(t[e]=s,this.#s){let r=this.#s-t[e];for(;this.#f>r;)this.#G(!0)}this.#f+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#f)}}#L=t=>{};#j=(t,e,s)=>{};#B=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#p;!(!this.#I(e)||((t||!this.#_(e))&&(yield e),e===this.#y));)e=this.#v[e]}*#M({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#y;!(!this.#I(e)||((t||!this.#_(e))&&(yield e),e===this.#p));)e=this.#d[e]}#I(t){return t!==void 0&&this.#u.get(this.#a[t])===t}*entries(){for(let t of this.#k())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*rentries(){for(let t of this.#M())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*keys(){for(let t of this.#k()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*rkeys(){for(let t of this.#M()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*values(){for(let t of this.#k())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}*rvalues(){for(let t of this.#M())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#k()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;if(r!==void 0&&t(r,this.#a[s],this))return this.get(this.#a[s],e)}}forEach(t,e=this){for(let s of this.#k()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}rforEach(t,e=this){for(let s of this.#M()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}purgeStale(){let t=!1;for(let e of this.#M({allowStale:!0}))this.#_(e)&&(this.#A(this.#a[e],"expire"),t=!0);return t}info(t){let e=this.#u.get(t);if(e===void 0)return;let s=this.#i[e],i=this.#l(s)?s.__staleWhileFetching:s;if(i===void 0)return;let r={value:i};if(this.#g&&this.#x){let h=this.#g[e],o=this.#x[e];if(h&&o){let a=h-(this.#c.now()-o);r.ttl=a,r.start=Date.now()}}return this.#O&&(r.size=this.#O[e]),r}dump(){let t=[];for(let e of this.#k({allowStale:!0})){let s=this.#a[e],i=this.#i[e],r=this.#l(i)?i.__staleWhileFetching:i;if(r===void 0||s===void 0)continue;let h={value:r};if(this.#g&&this.#x){h.ttl=this.#g[e];let o=this.#c.now()-this.#x[e];h.start=Math.floor(Date.now()-o)}this.#O&&(h.size=this.#O[e]),t.unshift([s,h])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#c.now()-i}this.set(e,s.value,s)}}set(t,e,s={}){if(e===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:a}=s,{noUpdateTTL:l=this.noUpdateTTL}=s,f=this.#B(t,e,s.size||0,o);if(this.maxEntrySize&&f>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#A(t,"set"),this;let c=this.#o===0?void 0:this.#u.get(t);if(c===void 0)c=this.#o===0?this.#p:this.#R.length!==0?this.#R.pop():this.#o===this.#t?this.#G(!1):this.#o,this.#a[c]=t,this.#i[c]=e,this.#u.set(t,c),this.#d[this.#p]=c,this.#v[c]=this.#p,this.#p=c,this.#o++,this.#j(c,f,a),a&&(a.set="add"),l=!1,this.#F&&this.#r?.(e,t,"add");else{this.#N(c);let d=this.#i[c];if(e!==d){if(this.#T&&this.#l(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:u}=d;u!==void 0&&!h&&(this.#E&&this.#n?.(u,t,"set"),this.#e&&this.#m?.push([u,t,"set"]))}else h||(this.#E&&this.#n?.(d,t,"set"),this.#e&&this.#m?.push([d,t,"set"]));if(this.#L(c),this.#j(c,f,a),this.#i[c]=e,a){a.set="replace";let u=d&&this.#l(d)?d.__staleWhileFetching:d;u!==void 0&&(a.oldValue=u)}}else a&&(a.set="update");this.#F&&this.onInsert?.(e,t,e===d?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(l||this.#W(c,i,r),a&&this.#D(a,c)),!h&&this.#e&&this.#m){let d=this.#m,u;for(;u=d?.shift();)this.#h?.(...u)}return this}pop(){try{for(;this.#o;){let t=this.#i[this.#y];if(this.#G(!0),this.#l(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#h?.(...e)}}}#G(t){let e=this.#y,s=this.#a[e],i=this.#i[e];return this.#T&&this.#l(i)?i.__abortController.abort(new Error("evicted")):(this.#E||this.#e)&&(this.#E&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#L(e),this.#b?.[e]&&(clearTimeout(this.#b[e]),this.#b[e]=void 0),t&&(this.#a[e]=void 0,this.#i[e]=void 0,this.#R.push(e)),this.#o===1?(this.#y=this.#p=0,this.#R.length=0):this.#y=this.#d[e],this.#u.delete(s),this.#o--,e}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,r=this.#u.get(t);if(r!==void 0){let h=this.#i[r];if(this.#l(h)&&h.__staleWhileFetching===void 0)return!1;if(this.#_(r))i&&(i.has="stale",this.#D(i,r));else return s&&this.#C(r),i&&(i.has="hit",this.#D(i,r)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{allowStale:s=this.allowStale}=e,i=this.#u.get(t);if(i===void 0||!s&&this.#_(i))return;let r=this.#i[i];return this.#l(r)?r.__staleWhileFetching:r}#z(t,e,s,i){let r=e===void 0?void 0:this.#i[e];if(this.#l(r))return r;let h=new Lt,{signal:o}=s;o?.addEventListener("abort",()=>h.abort(o.reason),{signal:h.signal});let a={signal:h.signal,options:s,context:i},l=(p,b=!1)=>{let{aborted:w}=h.signal,v=s.ignoreFetchAbort&&p!==void 0,E=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&p!==void 0);if(s.status&&(w&&!b?(s.status.fetchAborted=!0,s.status.fetchError=h.signal.reason,v&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),w&&!v&&!b)return c(h.signal.reason,E);let y=u,S=this.#i[e];return(S===u||v&&b&&S===void 0)&&(p===void 0?y.__staleWhileFetching!==void 0?this.#i[e]=y.__staleWhileFetching:this.#A(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,p,a.options))),p},f=p=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=p),c(p,!1)),c=(p,b)=>{let{aborted:w}=h.signal,v=w&&s.allowStaleOnFetchAbort,E=v||s.allowStaleOnFetchRejection,y=E||s.noDeleteOnFetchRejection,S=u;if(this.#i[e]===u&&(!y||!b&&S.__staleWhileFetching===void 0?this.#A(t,"fetch"):v||(this.#i[e]=S.__staleWhileFetching)),E)return s.status&&S.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),S.__staleWhileFetching;if(S.__returned===S)throw p},d=(p,b)=>{let w=this.#S?.(t,r,a);w&&w instanceof Promise&&w.then(v=>p(v===void 0?void 0:v),b),h.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(p(void 0),s.allowStaleOnFetchAbort&&(p=v=>l(v,!0)))})};s.status&&(s.status.fetchDispatched=!0);let u=new Promise(d).then(l,f),m=Object.assign(u,{__abortController:h,__staleWhileFetching:r,__returned:void 0});return e===void 0?(this.set(t,m,{...a.options,status:void 0}),e=this.#u.get(t)):this.#i[e]=m,m}#l(t){if(!this.#T)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof Lt}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:f=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:b=!1,status:w,signal:v}=e;if(!this.#T)return w&&(w.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,status:w});let E={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,ttl:h,noDisposeOnSet:o,size:a,sizeCalculation:l,noUpdateTTL:f,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:u,status:w,signal:v},y=this.#u.get(t);if(y===void 0){w&&(w.fetch="miss");let S=this.#z(t,y,E,p);return S.__returned=S}else{let S=this.#i[y];if(this.#l(S)){let st=s&&S.__staleWhileFetching!==void 0;return w&&(w.fetch="inflight",st&&(w.returnedStale=!0)),st?S.__staleWhileFetching:S.__returned=S}let B=this.#_(y);if(!b&&!B)return w&&(w.fetch="hit"),this.#N(y),i&&this.#C(y),w&&this.#D(w,y),S;let U=this.#z(t,y,E,p),et=U.__staleWhileFetching!==void 0&&s;return w&&(w.fetch=B?"stale":"refresh",et&&B&&(w.returnedStale=!0)),et?U.__staleWhileFetching:U.__returned=U}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:r,...h}=e,o=this.get(t,h);if(!r&&o!==void 0)return o;let a=s(t,o,{options:h,context:i});return this.set(t,a,h),a}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:h}=e,o=this.#u.get(t);if(o!==void 0){let a=this.#i[o],l=this.#l(a);return h&&this.#D(h,o),this.#_(o)?(h&&(h.get="stale"),l?(h&&s&&a.__staleWhileFetching!==void 0&&(h.returnedStale=!0),s?a.__staleWhileFetching:void 0):(r||this.#A(t,"expire"),h&&s&&(h.returnedStale=!0),s?a:void 0)):(h&&(h.get="hit"),l?a.__staleWhileFetching:(this.#N(o),i&&this.#C(o),a))}else h&&(h.get="miss")}#U(t,e){this.#v[e]=t,this.#d[t]=e}#N(t){t!==this.#p&&(t===this.#y?this.#y=this.#d[t]:this.#U(this.#v[t],this.#d[t]),this.#U(this.#p,t),this.#p=t)}delete(t){return this.#A(t,"delete")}#A(t,e){let s=!1;if(this.#o!==0){let i=this.#u.get(t);if(i!==void 0)if(this.#b?.[i]&&(clearTimeout(this.#b?.[i]),this.#b[i]=void 0),s=!0,this.#o===1)this.#q(e);else{this.#L(i);let r=this.#i[i];if(this.#l(r)?r.__abortController.abort(new Error("deleted")):(this.#E||this.#e)&&(this.#E&&this.#n?.(r,t,e),this.#e&&this.#m?.push([r,t,e])),this.#u.delete(t),this.#a[i]=void 0,this.#i[i]=void 0,i===this.#p)this.#p=this.#v[i];else if(i===this.#y)this.#y=this.#d[i];else{let h=this.#v[i];this.#d[h]=this.#d[i];let o=this.#d[i];this.#v[o]=this.#v[i]}this.#o--,this.#R.push(i)}}if(this.#e&&this.#m?.length){let i=this.#m,r;for(;r=i?.shift();)this.#h?.(...r)}return s}clear(){return this.#q("delete")}#q(t){for(let e of this.#M({allowStale:!0})){let s=this.#i[e];if(this.#l(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#a[e];this.#E&&this.#n?.(s,i,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#u.clear(),this.#i.fill(void 0),this.#a.fill(void 0),this.#g&&this.#x){this.#g.fill(0),this.#x.fill(0);for(let e of this.#b??[])e!==void 0&&clearTimeout(e);this.#b?.fill(void 0)}if(this.#O&&this.#O.fill(0),this.#y=0,this.#p=0,this.#R.length=0,this.#f=0,this.#o=0,this.#e&&this.#m){let e=this.#m,s;for(;s=e?.shift();)this.#h?.(...s)}}};Wt.LRUCache=rr});var Oe=R(P=>{"use strict";var nr=P&&P.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(P,"__esModule",{value:!0});P.Minipass=P.isWritable=P.isReadable=P.isStream=void 0;var ds=typeof process=="object"&&process?process:{stdout:null,stderr:null},_e=require("node:events"),ws=nr(require("node:stream")),hr=require("node:string_decoder"),or=n=>!!n&&typeof n=="object"&&(n instanceof qt||n instanceof ws.default||(0,P.isReadable)(n)||(0,P.isWritable)(n));P.isStream=or;var ar=n=>!!n&&typeof n=="object"&&n instanceof _e.EventEmitter&&typeof n.pipe=="function"&&n.pipe!==ws.default.Writable.prototype.pipe;P.isReadable=ar;var lr=n=>!!n&&typeof n=="object"&&n instanceof _e.EventEmitter&&typeof n.write=="function"&&typeof n.end=="function";P.isWritable=lr;var $=Symbol("EOF"),q=Symbol("maybeEmitEnd"),K=Symbol("emittedEnd"),Bt=Symbol("emittingEnd"),lt=Symbol("emittedError"),It=Symbol("closed"),ps=Symbol("read"),Gt=Symbol("flush"),ms=Symbol("flushChunk"),L=Symbol("encoding"),rt=Symbol("decoder"),x=Symbol("flowing"),ct=Symbol("paused"),nt=Symbol("resume"),T=Symbol("buffer"),M=Symbol("pipes"),C=Symbol("bufferLength"),we=Symbol("bufferPush"),zt=Symbol("bufferShift"),k=Symbol("objectMode"),O=Symbol("destroyed"),be=Symbol("error"),ye=Symbol("emitData"),gs=Symbol("emitEnd"),Se=Symbol("emitEnd2"),I=Symbol("async"),ve=Symbol("abort"),Ut=Symbol("aborted"),ut=Symbol("signal"),Z=Symbol("dataListeners"),D=Symbol("discarded"),ft=n=>Promise.resolve().then(n),cr=n=>n(),ur=n=>n==="end"||n==="finish"||n==="prefinish",fr=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,dr=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),$t=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[nt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ee=class extends $t{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},pr=n=>!!n.objectMode,mr=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",qt=class extends _e.EventEmitter{[x]=!1;[ct]=!1;[M]=[];[T]=[];[k];[L];[I];[rt];[$]=!1;[K]=!1;[Bt]=!1;[It]=!1;[lt]=null;[C]=0;[O]=!1;[ut];[Ut]=!1;[Z]=0;[D]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");pr(e)?(this[k]=!0,this[L]=null):mr(e)?(this[L]=e.encoding,this[k]=!1):(this[k]=!1,this[L]=null),this[I]=!!e.async,this[rt]=this[L]?new hr.StringDecoder(this[L]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[T]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[M]});let{signal:s}=e;s&&(this[ut]=s,s.aborted?this[ve]():s.addEventListener("abort",()=>this[ve]()))}get bufferLength(){return this[C]}get encoding(){return this[L]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[k]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[I]}set async(t){this[I]=this[I]||!!t}[ve](){this[Ut]=!0,this.emit("abort",this[ut]?.reason),this.destroy(this[ut]?.reason)}get aborted(){return this[Ut]}set aborted(t){}write(t,e,s){if(this[Ut])return!1;if(this[$])throw new Error("write after end");if(this[O])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[I]?ft:cr;if(!this[k]&&!Buffer.isBuffer(t)){if(dr(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(fr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[k]?(this[x]&&this[C]!==0&&this[Gt](!0),this[x]?this.emit("data",t):this[we](t),this[C]!==0&&this.emit("readable"),s&&i(s),this[x]):t.length?(typeof t=="string"&&!(e===this[L]&&!this[rt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[L]&&(t=this[rt].write(t)),this[x]&&this[C]!==0&&this[Gt](!0),this[x]?this.emit("data",t):this[we](t),this[C]!==0&&this.emit("readable"),s&&i(s),this[x]):(this[C]!==0&&this.emit("readable"),s&&i(s),this[x])}read(t){if(this[O])return null;if(this[D]=!1,this[C]===0||t===0||t&&t>this[C])return this[q](),null;this[k]&&(t=null),this[T].length>1&&!this[k]&&(this[T]=[this[L]?this[T].join(""):Buffer.concat(this[T],this[C])]);let e=this[ps](t||null,this[T][0]);return this[q](),e}[ps](t,e){if(this[k])this[zt]();else{let s=e;t===s.length||t===null?this[zt]():typeof s=="string"?(this[T][0]=s.slice(t),e=s.slice(0,t),this[C]-=t):(this[T][0]=s.subarray(t),e=s.subarray(0,t),this[C]-=t)}return this.emit("data",e),!this[T].length&&!this[$]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[$]=!0,this.writable=!1,(this[x]||!this[ct])&&this[q](),this}[nt](){this[O]||(!this[Z]&&!this[M].length&&(this[D]=!0),this[ct]=!1,this[x]=!0,this.emit("resume"),this[T].length?this[Gt]():this[$]?this[q]():this.emit("drain"))}resume(){return this[nt]()}pause(){this[x]=!1,this[ct]=!0,this[D]=!1}get destroyed(){return this[O]}get flowing(){return this[x]}get paused(){return this[ct]}[we](t){this[k]?this[C]+=1:this[C]+=t.length,this[T].push(t)}[zt](){return this[k]?this[C]-=1:this[C]-=this[T][0].length,this[T].shift()}[Gt](t=!1){do;while(this[ms](this[zt]())&&this[T].length);!t&&!this[T].length&&!this[$]&&this.emit("drain")}[ms](t){return this.emit("data",t),this[x]}pipe(t,e){if(this[O])return t;this[D]=!1;let s=this[K];return e=e||{},t===ds.stdout||t===ds.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[M].push(e.proxyErrors?new Ee(this,t,e):new $t(this,t,e)),this[I]?ft(()=>this[nt]()):this[nt]()),t}unpipe(t){let e=this[M].find(s=>s.dest===t);e&&(this[M].length===1?(this[x]&&this[Z]===0&&(this[x]=!1),this[M]=[]):this[M].splice(this[M].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[D]=!1,this[Z]++,!this[M].length&&!this[x]&&this[nt]();else if(t==="readable"&&this[C]!==0)super.emit("readable");else if(ur(t)&&this[K])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[lt]){let i=e;this[I]?ft(()=>i.call(this,this[lt])):i.call(this,this[lt])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Z]=this.listeners("data").length,this[Z]===0&&!this[D]&&!this[M].length&&(this[x]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Z]=0,!this[D]&&!this[M].length&&(this[x]=!1)),e}get emittedEnd(){return this[K]}[q](){!this[Bt]&&!this[K]&&!this[O]&&this[T].length===0&&this[$]&&(this[Bt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[It]&&this.emit("close"),this[Bt]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==O&&this[O])return!1;if(t==="data")return!this[k]&&!s?!1:this[I]?(ft(()=>this[ye](s)),!0):this[ye](s);if(t==="end")return this[gs]();if(t==="close"){if(this[It]=!0,!this[K]&&!this[O])return!1;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(t==="error"){this[lt]=s,super.emit(be,s);let r=!this[ut]||this.listeners("error").length?super.emit("error",s):!1;return this[q](),r}else if(t==="resume"){let r=super.emit("resume");return this[q](),r}else if(t==="finish"||t==="prefinish"){let r=super.emit(t);return this.removeAllListeners(t),r}let i=super.emit(t,...e);return this[q](),i}[ye](t){for(let s of this[M])s.dest.write(t)===!1&&this.pause();let e=this[D]?!1:super.emit("data",t);return this[q](),e}[gs](){return this[K]?!1:(this[K]=!0,this.readable=!1,this[I]?(ft(()=>this[Se]()),!0):this[Se]())}[Se](){if(this[rt]){let e=this[rt].end();if(e){for(let s of this[M])s.dest.write(e);this[D]||super.emit("data",e)}}for(let e of this[M])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[k]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[k]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[k])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[L]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(O,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[D]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[$])return e();let r,h,o=c=>{this.off("data",a),this.off("end",l),this.off(O,f),e(),h(c)},a=c=>{this.off("error",o),this.off("end",l),this.off(O,f),this.pause(),r({value:c,done:!!this[$]})},l=()=>{this.off("error",o),this.off("data",a),this.off(O,f),e(),r({done:!0,value:void 0})},f=()=>o(new Error("stream destroyed"));return new Promise((c,d)=>{h=d,r=c,this.once(O,f),this.once("error",o),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[D]=!1;let t=!1,e=()=>(this.pause(),this.off(be,e),this.off(O,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(be,e),this.once(O,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[O])return t?this.emit("error",t):this.emit(O),this;this[O]=!0,this[D]=!0,this[T].length=0,this[C]=0;let e=this;return typeof e.close=="function"&&!this[It]&&e.close(),t?this.emit("error",t):this.emit(O),this}static get isStream(){return P.isStream}};P.Minipass=qt});var Ms=R(_=>{"use strict";var gr=_&&_.__createBinding||(Object.create?(function(n,t,e,s){s===void 0&&(s=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,s,i)}):(function(n,t,e,s){s===void 0&&(s=e),n[s]=t[e]})),wr=_&&_.__setModuleDefault||(Object.create?(function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}):function(n,t){n.default=t}),br=_&&_.__importStar||function(n){if(n&&n.__esModule)return n;var t={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&gr(t,n,e);return wr(t,n),t};Object.defineProperty(_,"__esModule",{value:!0});_.PathScurry=_.Path=_.PathScurryDarwin=_.PathScurryPosix=_.PathScurryWin32=_.PathScurryBase=_.PathPosix=_.PathWin32=_.PathBase=_.ChildrenCache=_.ResolveCache=void 0;var Qt=fs(),Yt=require("node:path"),yr=require("node:url"),pt=require("fs"),Sr=br(require("node:fs")),vr=pt.realpathSync.native,Ht=require("node:fs/promises"),bs=Oe(),mt={lstatSync:pt.lstatSync,readdir:pt.readdir,readdirSync:pt.readdirSync,readlinkSync:pt.readlinkSync,realpathSync:vr,promises:{lstat:Ht.lstat,readdir:Ht.readdir,readlink:Ht.readlink,realpath:Ht.realpath}},_s=n=>!n||n===mt||n===Sr?mt:{...mt,...n,promises:{...mt.promises,...n.promises||{}}},Os=/^\\\\\?\\([a-z]:)\\?$/i,Er=n=>n.replace(/\//g,"\\").replace(Os,"$1\\"),_r=/[\\\/]/,N=0,xs=1,Ts=2,G=4,Cs=6,Rs=8,Q=10,As=12,j=15,dt=~j,xe=16,ys=32,gt=64,W=128,Vt=256,Xt=512,Ss=gt|W|Xt,Or=1023,Te=n=>n.isFile()?Rs:n.isDirectory()?G:n.isSymbolicLink()?Q:n.isCharacterDevice()?Ts:n.isBlockDevice()?Cs:n.isSocket()?As:n.isFIFO()?xs:N,vs=new Qt.LRUCache({max:2**12}),wt=n=>{let t=vs.get(n);if(t)return t;let e=n.normalize("NFKD");return vs.set(n,e),e},Es=new Qt.LRUCache({max:2**12}),Kt=n=>{let t=Es.get(n);if(t)return t;let e=wt(n.toLowerCase());return Es.set(n,e),e},bt=class extends Qt.LRUCache{constructor(){super({max:256})}};_.ResolveCache=bt;var Jt=class extends Qt.LRUCache{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}};_.ChildrenCache=Jt;var ks=Symbol("PathScurry setAsCwd"),A=class{name;root;roots;parent;nocase;isCWD=!1;#t;#s;get dev(){return this.#s}#n;get mode(){return this.#n}#r;get nlink(){return this.#r}#h;get uid(){return this.#h}#S;get gid(){return this.#S}#w;get rdev(){return this.#w}#c;get blksize(){return this.#c}#o;get ino(){return this.#o}#f;get size(){return this.#f}#u;get blocks(){return this.#u}#a;get atimeMs(){return this.#a}#i;get mtimeMs(){return this.#i}#d;get ctimeMs(){return this.#d}#v;get birthtimeMs(){return this.#v}#y;get atime(){return this.#y}#p;get mtime(){return this.#p}#R;get ctime(){return this.#R}#m;get birthtime(){return this.#m}#O;#x;#g;#b;#E;#T;#e;#F;#P;#C;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=N,s,i,r,h,o){this.name=t,this.#O=r?Kt(t):wt(t),this.#e=e&Or,this.nocase=r,this.roots=i,this.root=s||this,this.#F=h,this.#g=o.fullpath,this.#E=o.relative,this.#T=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=_s(o.fs)}depth(){return this.#x!==void 0?this.#x:this.parent?this.#x=this.parent.depth()+1:this.#x=0}childrenCache(){return this.#F}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#D(i):this.#D(i)}#D(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#F.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#F.set(this,e),this.#e&=~xe,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?Kt(t):wt(t);for(let a of s)if(a.#O===i)return a;let r=this.parent?this.sep:"",h=this.#g?this.#g+r+t:void 0,o=this.newChild(t,N,{...e,parent:this,fullpath:h});return this.canReaddir()||(o.#e|=W),s.push(o),o}relative(){if(this.isCWD)return"";if(this.#E!==void 0)return this.#E;let t=this.name,e=this.parent;if(!e)return this.#E=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#T!==void 0)return this.#T;let t=this.name,e=this.parent;if(!e)return this.#T=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=i}fullpathPosix(){if(this.#b!==void 0)return this.#b;if(this.sep==="/")return this.#b=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#b=`//?/${i}`:this.#b=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#b=s}isUnknown(){return(this.#e&j)===N}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&j)===Rs}isDirectory(){return(this.#e&j)===G}isCharacterDevice(){return(this.#e&j)===Ts}isBlockDevice(){return(this.#e&j)===Cs}isFIFO(){return(this.#e&j)===xs}isSocket(){return(this.#e&j)===As}isSymbolicLink(){return(this.#e&Q)===Q}lstatCached(){return this.#e&ys?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#C}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let t=this.#e&j;return!(t!==N&&t!==Q||this.#e&Vt||this.#e&W)}calledReaddir(){return!!(this.#e&xe)}isENOENT(){return!!(this.#e&W)}isNamed(t){return this.nocase?this.#O===Kt(t):this.#O===wt(t)}async readlink(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#P=s}catch(e){this.#M(e.code);return}}readlinkSync(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#P=s}catch(e){this.#M(e.code);return}}#W(t){this.#e|=xe;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let r=s.slice(0,s.provisional);e?t(null,r):queueMicrotask(()=>t(null,r));return}if(this.#N.push(t),this.#A)return;this.#A=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(r,h)=>{if(r)this.#B(r.code),s.provisional=0;else{for(let o of h)this.#I(o,s);this.#W(s)}this.#q(s.slice(0,s.provisional))})}#H;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#H)await this.#H;else{let s=()=>{};this.#H=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#I(i,t);this.#W(t)}catch(i){this.#B(i.code),t.provisional=0}this.#H=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#I(s,t);this.#W(t)}catch(s){this.#B(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&Ss)return!1;let t=j&this.#e;return t===N||t===G||t===Q}shouldWalk(t,e){return(this.#e&G)===G&&!(this.#e&Ss)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#C)return this.#C;if(!((Xt|Vt|W)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#C=this.resolve(t)}catch{this.#L()}}realpathSync(){if(this.#C)return this.#C;if(!((Xt|Vt|W)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#C=this.resolve(t)}catch{this.#L()}}[ks](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#E=s.join(this.sep),i.#T=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#E=void 0,i.#T=void 0,i=i.parent}};_.PathBase=A;var yt=class n extends A{sep="\\";splitSep=_r;constructor(t,e=N,s,i,r,h,o){super(t,e,s,i,r,h,o)}newChild(t,e=N,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return Yt.win32.parse(t).root}getRoot(t){if(t=Er(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new Et(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Os,"$1\\"),t===e}};_.PathWin32=yt;var St=class n extends A{splitSep="/";sep="/";constructor(t,e=N,s,i,r,h,o){super(t,e,s,i,r,h,o)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=N,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}};_.PathPosix=St;var vt=class{root;rootPath;roots;cwd;#t;#s;#n;nocase;#r;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:r=16*1024,fs:h=mt}={}){this.#r=_s(h),(t instanceof URL||t.startsWith("file://"))&&(t=(0,yr.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new bt,this.#s=new bt,this.#n=new Jt(r);let a=o.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let l=this.root,f=a.length-1,c=e.sep,d=this.rootPath,u=!1;for(let m of a){let p=f--;l=l.child(m,{relative:new Array(p).fill("..").join(c),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(u?"":c)+m}),u=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let r=t.length-1;r>=0;r--){let h=t[r];if(!(!h||h===".")&&(e=e?`${h}/${e}`:h,this.isAbsolute(h)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let r=t.length-1;r>=0;r--){let h=t[r];if(!(!h||h===".")&&(e=e?`${h}/${e}`:h,this.isAbsolute(h)))break}let s=this.#s.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(r=>r.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=[];(!r||r(t))&&o.push(s?t:t.fullpath());let a=new Set,l=(c,d)=>{a.add(c),c.readdirCB((u,m)=>{if(u)return d(u);let p=m.length;if(!p)return d();let b=()=>{--p===0&&d()};for(let w of m)(!r||r(w))&&o.push(s?w:w.fullpath()),i&&w.isSymbolicLink()?w.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(a,h)?l(v,b):b()):w.shouldWalk(a,h)?l(w,b):b()},!0)},f=t;return new Promise((c,d)=>{l(f,u=>{if(u)return d(u);c(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=[];(!r||r(t))&&o.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let f=l.readdirSync();for(let c of f){(!r||r(c))&&o.push(s?c:c.fullpath());let d=c;if(c.isSymbolicLink()){if(!(i&&(d=c.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,h)&&a.add(d)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e;(!r||r(t))&&(yield s?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let f of l){(!r||r(f))&&(yield s?f:f.fullpath());let c=f;if(f.isSymbolicLink()){if(!(i&&(c=f.realpathSync())))continue;c.isUnknown()&&c.lstatSync()}c.shouldWalk(o,h)&&o.add(c)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=new bs.Minipass({objectMode:!0});(!r||r(t))&&o.write(s?t:t.fullpath());let a=new Set,l=[t],f=0,c=()=>{let d=!1;for(;!d;){let u=l.shift();if(!u){f===0&&o.end();return}f++,a.add(u);let m=(b,w,v=!1)=>{if(b)return o.emit("error",b);if(i&&!v){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(S=>S?.isUnknown()?S.lstat():S));if(E.length){Promise.all(E).then(()=>m(null,w,!0));return}}for(let E of w)E&&(!r||r(E))&&(o.write(s?E:E.fullpath())||(d=!0));f--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,h)&&l.push(y)}d&&!o.flowing?o.once("drain",c):p||c()},p=!0;u.readdirCB(m,!0),p=!1}};return c(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=new bs.Minipass({objectMode:!0}),a=new Set;(!r||r(t))&&o.write(s?t:t.fullpath());let l=[t],f=0,c=()=>{let d=!1;for(;!d;){let u=l.shift();if(!u){f===0&&o.end();return}f++,a.add(u);let m=u.readdirSync();for(let p of m)(!r||r(p))&&(o.write(s?p:p.fullpath())||(d=!0));f--;for(let p of m){let b=p;if(p.isSymbolicLink()){if(!(i&&(b=p.realpathSync())))continue;b.isUnknown()&&b.lstatSync()}b.shouldWalk(a,h)&&l.push(b)}}d&&!o.flowing&&o.once("drain",c)};return c(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[ks](e)}};_.PathScurryBase=vt;var Et=class extends vt{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,Yt.win32,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return Yt.win32.parse(t).root.toUpperCase()}newRoot(t){return new yt(this.rootPath,G,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}};_.PathScurryWin32=Et;var _t=class extends vt{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,Yt.posix,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new St(this.rootPath,G,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}};_.PathScurryPosix=_t;var Zt=class extends _t{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}};_.PathScurryDarwin=Zt;_.Path=process.platform==="win32"?yt:St;_.PathScurry=process.platform==="win32"?Et:process.platform==="darwin"?Zt:_t});var Re=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.Pattern=void 0;var xr=H(),Tr=n=>n.length>=1,Cr=n=>n.length>=1,Rr=Symbol.for("nodejs.util.inspect.custom"),Ce=class n{#t;#s;#n;length;#r;#h;#S;#w;#c;#o;#f=!0;constructor(t,e,s,i){if(!Tr(t))throw new TypeError("empty pattern list");if(!Cr(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#s=e,this.#n=s,this.#r=i,this.#n===0){if(this.isUNC()){let[r,h,o,a,...l]=this.#t,[f,c,d,u,...m]=this.#s;l[0]===""&&(l.shift(),m.shift());let p=[r,h,o,a,""].join("/"),b=[f,c,d,u,""].join("/");this.#t=[p,...l],this.#s=[b,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[r,...h]=this.#t,[o,...a]=this.#s;h[0]===""&&(h.shift(),a.shift());let l=r+"/",f=o+"/";this.#t=[l,...h],this.#s=[f,...a],this.length=this.#t.length}}}[Rr](){return"Pattern <"+this.#s.slice(this.#n).join("/")+">"}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===xr.GLOBSTAR}isRegExp(){return this.#t[this.#n]instanceof RegExp}globString(){return this.#S=this.#S||(this.#n===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#h!==void 0?this.#h:this.hasMore()?(this.#h=new n(this.#t,this.#s,this.#n+1,this.#r),this.#h.#o=this.#o,this.#h.#c=this.#c,this.#h.#w=this.#w,this.#h):this.#h=null}isUNC(){let t=this.#t;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#w!==void 0?this.#w:this.#w=this.#r==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#o!==void 0?this.#o:this.#o=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#f)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#f?!1:(this.#f=!1,!0)}};te.Pattern=Ce});var ke=R(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.Ignore=void 0;var Ps=H(),Ar=Re(),kr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ae=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:r,platform:h=kr}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=h,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:r,optimizationLevel:2,platform:h,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new Ps.Minimatch(t,this.mmopts);for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.Processor=z.SubWalks=z.MatchRecord=z.HasWalkedCache=void 0;var Ds=H(),se=class n{store;constructor(t=new Map){this.store=t}copy(){return new n(new Map(this.store))}hasWalked(t,e){return this.store.get(t.fullpath())?.has(e.globString())}storeWalked(t,e){let s=t.fullpath(),i=this.store.get(s);i?i.add(e.globString()):this.store.set(s,new Set([e.globString()]))}};z.HasWalkedCache=se;var ie=class{store=new Map;add(t,e,s){let i=(e?2:0)|(s?1:0),r=this.store.get(t);this.store.set(t,r===void 0?i:i&r)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}};z.MatchRecord=ie;var re=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}};z.SubWalks=re;var Me=class n{hasWalkedCache;matches=new ie;subwalks=new re;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new se}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,r]of s){this.hasWalkedCache.storeWalked(i,r);let h=r.root(),o=r.isAbsolute()&&this.opts.absolute!==!1;if(h){i=i.resolve(h==="/"&&this.opts.root!==void 0?this.opts.root:h);let c=r.rest();if(c)r=c;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let a,l,f=!1;for(;typeof(a=r.pattern())=="string"&&(l=r.rest());)i=i.resolve(a),r=l,f=!0;if(a=r.pattern(),l=r.rest(),f){if(this.hasWalkedCache.hasWalked(i,r))continue;this.hasWalkedCache.storeWalked(i,r)}if(typeof a=="string"){let c=a===".."||a===""||a===".";this.matches.add(i.resolve(a),o,c);continue}else if(a===Ds.GLOBSTAR){(!i.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(i,r);let c=l?.pattern(),d=l?.rest();if(!l||(c===""||c===".")&&!d)this.matches.add(i,o,c===""||c===".");else if(c===".."){let u=i.parent||i;d?this.hasWalkedCache.hasWalked(u,d)||this.subwalks.add(u,d):this.matches.add(u,o,!0)}}else a instanceof RegExp&&this.subwalks.add(i,r)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let r of e)for(let h of s){let o=h.isAbsolute(),a=h.pattern(),l=h.rest();a===Ds.GLOBSTAR?i.testGlobstar(r,h,l,o):a instanceof RegExp?i.testRegExp(r,a,l,o):i.testString(r,a,l,o)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let r=s.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(t,r,s.rest(),i);else if(r===".."){let h=t.parent||t;this.subwalks.add(h,s)}else r instanceof RegExp&&this.testRegExp(t,r,s.rest(),i)}}testRegExp(t,e,s,i){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};z.Processor=Me});var Ls=R(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.GlobStream=X.GlobWalker=X.GlobUtil=void 0;var Mr=Oe(),js=ke(),Ns=Fs(),Pr=(n,t)=>typeof n=="string"?new js.Ignore([n],t):Array.isArray(n)?new js.Ignore(n,t):n,Ot=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#n;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#n=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#s=Pr(s.ignore??[],s),!this.includeChildMatches&&typeof this.#s.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#r(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#h(t){return!!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let h=await r.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat()}return this.matchCheckTest(r,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#r(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let h=r.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync()}return this.matchCheckTest(r,e)}matchFinish(t,e){if(this.#r(t))return;if(!this.includeChildMatches&&this.#s?.add){let r=`${t.relativePosix()}/**`;this.#s.add(r)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let r=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(r+i)}else{let r=this.opts.posix?t.relativePosix():t.relative(),h=this.opts.dotRelative&&!r.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(r?h+r+i:"."+i)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.matchFinish(i,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Ns.Processor(this.opts),s)}walkCB2(t,e,s,i){if(this.#h(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||(r++,this.match(o,a,l).then(()=>h()));for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,s,h):o.readdirCB((l,f)=>this.walkCB3(o,f,s,h),!0)}h()}walkCB3(t,e,s,i){s=s.filterEntries(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||(r++,this.match(o,a,l).then(()=>h()));for(let[o,a]of s.subwalks.entries())r++,this.walkCB2(o,a,s.child(),h);h()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Ns.Processor(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#h(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||this.matchSync(o,a,l);for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let a=o.readdirSync();this.walkCB3Sync(o,a,s,h)}h()}walkCB3Sync(t,e,s,i){s=s.filterEntries(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||this.matchSync(o,a,l);for(let[o,a]of s.subwalks.entries())r++,this.walkCB2Sync(o,a,s.child(),h);h()}};X.GlobUtil=Ot;var Pe=class extends Ot{matches=new Set;constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}};X.GlobWalker=Pe;var De=class extends Ot{results;constructor(t,e,s){super(t,e,s),this.results=new Mr.Minipass({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};X.GlobStream=De});var je=R(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.Glob=void 0;var Dr=H(),Fr=require("node:url"),ne=Ms(),jr=Re(),he=Ls(),Nr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Fe=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,Fr.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||Nr,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?ne.PathScurryWin32:e.platform==="darwin"?ne.PathScurryDarwin:e.platform?ne.PathScurryPosix:ne.PathScurry;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",i={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(a=>new Dr.Minimatch(a,i)),[h,o]=r.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=h.map((a,l)=>{let f=o[l];if(!f)throw new Error("invalid pattern object");return new jr.Pattern(a,f,0,this.platform)})}async walk(){return[...await new he.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new he.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new he.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new he.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};oe.Glob=Fe});var Ne=R(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.hasMagic=void 0;var Lr=H(),Wr=(n,t={})=>{Array.isArray(n)||(n=[n]);for(let e of n)if(new Lr.Minimatch(e,t).hasMagic())return!0;return!1};ae.hasMagic=Wr});Object.defineProperty(exports,"__esModule",{value:!0});exports.glob=exports.sync=exports.iterate=exports.iterateSync=exports.stream=exports.streamSync=exports.Ignore=exports.hasMagic=exports.Glob=exports.unescape=exports.escape=void 0;exports.globStreamSync=xt;exports.globStream=Le;exports.globSync=We;exports.globIterateSync=Tt;exports.globIterate=Be;var Ws=H(),tt=je(),Br=Ne(),Is=H();Object.defineProperty(exports,"escape",{enumerable:!0,get:function(){return Is.escape}});Object.defineProperty(exports,"unescape",{enumerable:!0,get:function(){return Is.unescape}});var Ir=je();Object.defineProperty(exports,"Glob",{enumerable:!0,get:function(){return Ir.Glob}});var Gr=Ne();Object.defineProperty(exports,"hasMagic",{enumerable:!0,get:function(){return Gr.hasMagic}});var zr=ke();Object.defineProperty(exports,"Ignore",{enumerable:!0,get:function(){return zr.Ignore}});function xt(n,t={}){return new tt.Glob(n,t).streamSync()}function Le(n,t={}){return new tt.Glob(n,t).stream()}function We(n,t={}){return new tt.Glob(n,t).walkSync()}async function Bs(n,t={}){return new tt.Glob(n,t).walk()}function Tt(n,t={}){return new tt.Glob(n,t).iterateSync()}function Be(n,t={}){return new tt.Glob(n,t).iterate()}exports.streamSync=xt;exports.stream=Object.assign(Le,{sync:xt});exports.iterateSync=Tt;exports.iterate=Object.assign(Be,{sync:Tt});exports.sync=Object.assign(We,{stream:xt,iterate:Tt});exports.glob=Object.assign(Bs,{glob:Bs,globSync:We,sync:exports.sync,globStream:Le,stream:exports.stream,globStreamSync:xt,streamSync:exports.streamSync,globIterate:Be,iterate:exports.iterate,globIterateSync:Tt,iterateSync:exports.iterateSync,Glob:tt.Glob,hasMagic:Br.hasMagic,escape:Ws.escape,unescape:Ws.unescape});exports.glob.glob=exports.glob; +"use strict";var C=(r,t)=>()=>{try{return t||r((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}};var ms=C(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.range=tt.balanced=void 0;var Ei=(r,t,e)=>{let s=r instanceof RegExp?ps(r,e):r,i=t instanceof RegExp?ps(t,e):t,n=s!==null&&i!=null&&(0,tt.range)(s,i,e);return n&&{start:n[0],end:n[1],pre:e.slice(0,n[0]),body:e.slice(n[0]+s.length,n[1]),post:e.slice(n[1]+i.length)}};tt.balanced=Ei;var ps=(r,t)=>{let e=t.match(r);return e?e[0]:null},Oi=(r,t,e)=>{let s,i,n,o,h,a=e.indexOf(r),l=e.indexOf(t,a+1),c=a;if(a>=0&&l>0){if(r===t)return[a,l];for(s=[],n=e.length;c>=0&&!h;){if(c===a)s.push(c),a=e.indexOf(r,c+1);else if(s.length===1){let u=s.pop();u!==void 0&&(h=[u,l])}else i=s.pop(),i!==void 0&&i=0?a:l}s.length&&o!==void 0&&(h=[n,o])}return h};tt.range=Oi});var vs=C(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.EXPANSION_MAX_REWRITES=T.EXPANSION_MAX_DEPTH=T.EXPANSION_MAX_LENGTH=T.EXPANSION_MAX=void 0;T.expand=Wi;var gs=ms(),ws="\0SLASH"+Math.random()+"\0",bs="\0OPEN"+Math.random()+"\0",xe="\0CLOSE"+Math.random()+"\0",ys="\0COMMA"+Math.random()+"\0",Ss="\0PERIOD"+Math.random()+"\0",xi=new RegExp(ws,"g"),Ci=new RegExp(bs,"g"),Mi=new RegExp(xe,"g"),ki=new RegExp(ys,"g"),Ai=new RegExp(Ss,"g"),Ri=/\\\\/g,Pi=/\\{/g,Ti=/\\}/g,Fi=/\\,/g,ji=/\\\./g;T.EXPANSION_MAX=1e5;T.EXPANSION_MAX_LENGTH=4e6;T.EXPANSION_MAX_DEPTH=1e3;T.EXPANSION_MAX_REWRITES=1e3;function _e(r){return isNaN(r)?r.charCodeAt(0):parseInt(r,10)}function Ni(r){return r.replace(Ri,ws).replace(Pi,bs).replace(Ti,xe).replace(Fi,ys).replace(ji,Ss)}function Di(r){return r.replace(xi,"\\").replace(Ci,"{").replace(Mi,"}").replace(ki,",").replace(Ai,".")}function Ee(r,t){for(let e=0;e=t}function ct(r,t,e,s,i,n){let o=[],h=0;for(let a=0;a=s)return o;let c=r[a]+t+e[l];if(!(n&&!c)){if(h+c.length>i)return o;o.push(c),h+=c.length}}return o}function $i(r,t,e,s){let i=r.split(/\.\./),n=[];if(i[0]===void 0||i[1]===void 0)return n;let o=_e(i[0]),h=_e(i[1]),a=Math.max(i[0].length,i[1].length),l=i.length===3&&i[2]!==void 0?Math.max(Math.abs(_e(i[2])),1):1,c=Gi;h0){let m=new Array(b+1).join("0");g<0?d="-"+m+d.slice(1):d=m+d}}if(p+d.length>s)break;n.push(d),p+=d.length}return n}function Oe(r,t,e,s,i,n,o){if(i>s)return[r];let h=[""],a=0,l=!1,c=!0;for(;;){let u=(0,gs.balanced)("{","}",r);if(!u)return ct(h,r,[""],t,e,l);let f=u.pre;if(/\$$/.test(f)){if(h=ct(h,f+"{"+u.body+"}",[""],t,e,l&&!u.post.length),c=!1,!u.post.length)break;r=u.post;continue}let p=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(u.body),g=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(u.body),d=p||g,b=u.body.indexOf(",")>=0;if(!d&&!b){if(a=t||v+U.length>e)break t;m.push(U),v+=U.length}}}}if(h=ct(h,f,m,t,e,l&&!u.post.length),!u.post.length)break;r=u.post}return h}});var Es=C(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.numericRange=void 0;var Me=(r,t)=>r===t?{t:"lit",ch:String(r)}:{t:"class",re:new RegExp(`^[${r}-${t}]$`)},Ce=(r,t)=>t.map(e=>[Me(r,r),...e]),ut=(r,t)=>{if(!r)return[[]];let e=+r[0],s=+t[0],i=r.slice(1),n=t.slice(1);if(e===s)return Ce(e,ut(i,n));let o="0".repeat(i.length),h="9".repeat(i.length),a=[];i!==o&&a.push(...Ce(e++,ut(i,h)));let l=n===h?[]:Ce(s--,ut(o,n));return e<=s&&a.push([Me(e,s),...Array.from(i,()=>Me(0,9))]),a.push(...l),a},_s=(r,t,e)=>{if(e)return ut(String(r).padStart(e,"0"),String(t).padStart(e,"0"));let s=[];for(let i=String(r).length;i<=String(t).length;i++){let n=Math.max(r,i===1?0:10**(i-1)),o=Math.min(t,10**i-1);s.push(...ut(String(n),String(o)))}return s},Ui=(r,t)=>{let e=Number(r),s=Number(t);if(!Number.isSafeInteger(e)||!Number.isSafeInteger(s))return;e>s&&([e,s]=[s,e]);let n=/^-?0\d/.test(r)||/^-?0\d/.test(t)?Math.max(r.length,t.length):0,o=[];if(e<0){let h=_s(Math.max(-s,1),-e,n&&n-1);o.push(...h.map(a=>[{t:"lit",ch:"-"},...a]))}return s>=0&&o.push(..._s(Math.max(e,0),s,n)),o};jt.numericRange=Ui});var Os=C(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.parseClass=void 0;var qi={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},ft=r=>r.replace(/[[\]\\-]/g,"\\$&"),ke=/$./,Hi=(r,t,e=!1,s)=>{let i=m=>{let y=s?m.normalize(s):m;return[...y].length===1?y:m},n=t;if(r.charAt(n)!=="[")throw new Error("not in a brace expression");let o=[],h=[],a=n+1,l=!1,c=!1,u=!1,f=n,p="";t:for(;ap.codePointAt(0)?o.push(ft(p)+"-"+ft(y)):y===p&&o.push(ft(y)),p="",a+=m.length;continue}if(r.startsWith("-]",a+m.length)){o.push(ft(y+"-")),a+=m.length+1;continue}if(r.startsWith("-",a+m.length)){p=y,a+=m.length+1;continue}o.push(ft(y)),a+=m.length}if(f{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.Matcher=void 0;var Xi=Es(),Ki=Os(),Ae={t:"match",id:0},Vi="!?+*@",et=r=>({t:"lit",ch:r}),Yi=r=>r.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),ks=r=>new RegExp(`^${Yi(r)}$`,"iu"),Dt=new Map,As=r=>{let t=Dt.get(r);return t||(t=ks(r),Dt.size>=1e3&&Dt.clear(),Dt.set(r,t)),t},Fe=(r,t)=>{if(t===r.ch)return!0;if(!r.re)return!1;let e=t.charCodeAt(0);if(e>=128)return r.re.test(t);let s=r.ascii??=new Uint8Array(128);return s[e]||=r.re.test(t)?1:2,s[e]===1},Ji=(r,t,e,s,i)=>{let n=[];for(let o=0;o{let t=new Map,e=[];return r.forEach((s,i)=>{s.t==="open"?e.push(i):s.t==="close"&&e.length&&t.set(e.pop(),i)}),t},Rs=(r,t,e,s,i)=>{let n=[],o=[n];for(let h=e;h{let e=[],s="",i=()=>{for(let n of s.normalize(t))e.push(et(n));s=""};for(let n of r){if(n.t==="lit"){s+=n.ch;continue}i(),e.push(n.t==="ext"?{...n,alts:n.alts.map(o=>Ps(o,t))}:n)}return i(),e},Qi=(r,t)=>{let e=1,s=h=>({t:"split",id:e++,out:h}),i=(h,a)=>h.reduceRight((l,c)=>n(c,l),a),n=(h,a)=>{switch(h.t){case"lit":let f=t?As(h.ch):void 0;return{t:"lit",id:e++,ch:h.ch,re:f,next:a};case"any":case"star":return{t:h.t,id:e++,next:a};case"class":return{t:"class",id:e++,re:h.re,next:a}}let l=f=>h.alts.map(p=>i(p,f));switch(h.type){case"@":return s(l(a));case"?":return s([a,...l(a)]);case"!":return{t:"neg",id:e++,sub:s(l(Ae)),next:a}}let c=s([]),u=s(l(c));return c.out.push(a,u),h.type==="*"?c:u};return[i(r,Ae),e]},tn=r=>{let t=[],e=new Set,s=n=>n.t==="match"?"match":String(n.id),i=(n,o)=>{if(n.t==="match"||e.has(n))return;e.add(n);let h=a=>t.push(`${o}${n.id}: ${a}`);switch(n.t){case"split":h(`split -> ${n.out.map(s).join(", ")}`);for(let a of n.out)i(a,o);return;case"neg":return h(`!(${s(n.sub)}) -> ${s(n.next)}`),i(n.sub,o+" "),i(n.next,o);case"lit":h(`${JSON.stringify(n.ch)} -> ${s(n.next)}`);break;case"class":h(`${n.re} -> ${s(n.next)}`);break;default:h(`${n.t==="any"?"?":"*"} -> ${s(n.next)}`)}i(n.next,o)};return i(r,""),[`start -> ${s(r)}`,...t].join(` +`)},Re=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(t){this.gen=t}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},Ts=(r,t)=>r.ids.length!==t.ids.length||r.runs.length!==t.runs.length||r.ids.some((e,s)=>e!==t.ids[s])?!1:r.runs.every(e=>t.runs.some(s=>s.neg===e.neg&&Ts(s.state,e.state))),xs=r=>({has:new Float64Array(r),seen:new Float64Array(r),gen:0}),dt=class{dots;dotStart;#t;constructor(t,e,s){this.dots=t,this.dotStart=e,this.#t=s}state(){return new Re(++this.#t.gen)}done(t){return t.ids=t.threads.map(e=>e.id).sort((e,s)=>e-s),t.match&&t.ids.unshift(Ae.id),t}#n(t,e){let{seen:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,!0)}#i(t,e){let{has:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,t.threads.push(e),!0)}restricted(t,e){return e&&(this.dots||this.dotStart&&t===0)}add(t,e,s,i){switch(e.t){case"split":if(!this.#n(t,e))return;for(let o of e.out)this.add(t,o,s,i);return;case"neg":if(!this.#n(t,e))return;let n=this.state();return this.add(n,e.sub,s,!1),this.done(n),this.addRun(t,{t:"run",neg:e,state:n},s,i);case"star":if(this.restricted(s,i))return;this.#i(t,e)&&this.add(t,e.next,s,i);return;case"match":t.match=!0;return;default:this.#i(t,e)}}addRun(t,e,s,i){for(let n of t.runs)if(n.neg===e.neg&&Ts(n.state,e.state))return;t.runs.push(e),e.state.match||this.add(t,e.neg.next,s,i)}step(t,e,s,i){let n=this.state();for(let o of t.threads)switch(o.t){case"lit":Fe(o,e)&&this.add(n,o.next,s+1,i);break;case"any":this.restricted(s,i)||this.add(n,o.next,s+1,i);break;case"class":!this.restricted(s,i)&&o.re.test(e)&&this.add(n,o.next,s+1,i);break;case"star":this.restricted(s,i)||this.add(n,o,s+1,i)}if(!this.restricted(s,i))for(let o of t.runs){if(o.state.dead){this.addRun(n,o,s+1,i);continue}let h=this.step(o.state,e,s,!1);this.addRun(n,{t:"run",neg:o.neg,state:h},s+1,i)}return this.done(n)}},Fs=r=>{let t=r.ids.join();if(!r.runs.length)return t;let e=r.runs.map(s=>`${s.neg.id}(${Fs(s.state)})`);return`${t}|${e.sort().join("|")}`},en=1<<18,Pe=class{#t;#n=new Map;#i=0;#o;#r;#d;#f;constructor(t,e){this.#t=t,this.#d=new dt(!1,!1,e),this.#f=new dt(!1,!0,e)}#u(t){return{state:t,match:t.match,dead:t.dead,next:new Map}}#h(t){let e=Fs(t),s=this.#n.get(e);if(s)return s;this.#i>en&&this.#m();let i=this.#u(t);return this.#n.set(e,i),this.#i+=e.length+1,i}#m(){this.#n.clear(),this.#i=0,this.#o=void 0,this.#r=void 0}start(t){if(t){if(this.#r)return this.#r;let s=this.#f.state();return this.#f.add(s,this.#t,0,!0),this.#r=this.#u(this.#f.done(s))}if(this.#o)return this.#o;let e=this.#d.state();return this.#d.add(e,this.#t,0,!0),this.#o=this.#h(this.#d.done(e))}next(t,e){let s=e.charCodeAt(0),i=s<128?void 0:t.next.get(e);if(i)return i;let n=t===this.#r?this.#h(this.#f.step(t.state,e,0,!0)):this.#h(this.#d.step(t.state,e,1,!0));return s<128?(t.ascii||(t.ascii=new Array(128),this.#i+=128),t.ascii[s]=n):t.next.set(e,n),this.#i++,n}},sn=r=>{let t=[];for(let e=r;e.t!=="match";e=e.next){if(e.t==="split"||e.t==="neg")return;t.push(e)}return t},nn=(r,t,e,s)=>{let i=0,n=e,o=-1,h=0;for(;n{let t=0,e=0;for(let s of r){let[i,n]=rn(s);t+=i,e+=n}return[t,e]},rn=r=>{if(r.t==="star")return[0,1/0];if(r.t!=="ext")return[1,1];if(r.type==="!")return[0,1/0];let t=r.alts.map(js),e=Math.min(...t.map(n=>n[0])),s=Math.max(...t.map(n=>n[1])),i=s===0?0:1/0;return r.type==="@"?[e,s]:r.type==="?"?[0,s]:r.type==="*"?[0,i]:[e,i]},Cs=(r,t,e)=>{for(let s=0;shn.test(r)?[...r]:r,Ms=r=>{if(r.includes("/"))throw new Error("can only match a single path portion, got: "+r)},Te=class{pattern;options;#t;#n;#i;#o;#r;#d=!1;#f;#u;#h=!1;#m=0;#l=1/0;#a=[];#s=[];#b;#E;#y=!1;#g;#w;constructor(t,e={}){if(t.includes("/"))throw new Error("can only match a single path portion, got pattern: "+t);this.pattern=t,this.options=e;let{nocase:s=!1,noext:i=!1,normalize:n}=e;this.#w=n===!0?"NFC":n||void 0;let o=/^[?*+@]\(\)$/.test(t),h=Ji(t,s,i||o,this.#w,e.rangeMark),[a]=Rs(h,Zi(h),0,h.length,!0);this.#w&&(a=Ps(a,this.#w));let[l,c]=Qi(a,s);if(this.#t=l,this.#n=c,a.every(u=>u.t==="lit"))this.#r=a.map(u=>u.ch).join(""),this.#d=s;else{let u=g=>g.t!=="lit"?void 0:s?{ch:g.ch,re:As(g.ch)}:{ch:g.ch};for(let g of a){let d=u(g);if(!d)break;this.#a.push(d)}for(let g=a.length-1;g>=0;g--){let d=u(a[g]);if(!d)break;this.#s.unshift(d)}this.#y=!!(this.#a.length||this.#s.length),s||(this.#b=this.#a.map(g=>g.ch).join(""),this.#E=this.#s.map(g=>g.ch).join("")),this.#u=sn(this.#t)?.slice(this.#a.length,-this.#s.length||void 0),this.#h=!!this.#u?.every(g=>g.t==="star"||g.t==="any");let[f,p]=js(a);this.#m=f,this.#l=p}}test(t){return this.#w?(Ms(t),this.#p(t.normalize(this.#w))):on.test(t)?(Ms(t),this.#p(t,[...t])):this.#p(t,t)}testUnchecked(t){return this.#p(this.#w?t.normalize(this.#w):t)}#p(t,e){if(this.#r!==void 0)return this.#d?(this.#f??=ks(this.#r)).test(t):t===this.#r;let s=this.#m,i=this.#l;if(e===void 0){let c=t.length,u=c+1>>1;if(ci)return!1;(ui)&&(e=Lt(t))}if(e!==void 0&&(e.lengthi))return!1;let n=this.#a.length;if(this.#y)if(this.#b!==void 0&&this.#E!==void 0){if(!t.startsWith(this.#b)||!t.endsWith(this.#E))return!1}else{e??=Lt(t);let c=e.length-this.#s.length;if(!Cs(this.#a,e,0)||!Cs(this.#s,e,c))return!1}let o=!this.options.dot&&t.startsWith(".");if(this.#u){if(t==="."||t===".."||o&&!n)return!1;if(this.#h)return!0;e??=Lt(t);let c=e.length-this.#s.length;return nn(this.#u,e,n,c)}if(e??=Lt(t),t==="."||t===".."){this.#i??=xs(this.#n);let c=this.#o??=new dt(!0,!1,this.#i),u=c.state();c.add(u,this.#t,0,!0);let f=c.done(u);for(let p=0;p{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.assertValidPattern=void 0;var an=1024*64,ln=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>an)throw new TypeError("pattern is too long")};zt.assertValidPattern=ln});var je=C(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.escape=void 0;var cn=(r,{windowsPathsNoEscape:t=!1,magicalBraces:e=!1}={})=>e?t?r.replace(/[?*()[\]{}]/g,"[$&]"):r.replace(/[?*()[\]\\{}]/g,"\\$&"):t?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");Bt.escape=cn});var Ne=C(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.unescape=void 0;var un=(r,{windowsPathsNoEscape:t=!1,magicalBraces:e=!0}={})=>e?t?r.replace(/\[([^/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):t?r.replace(/\[([^/\\{}])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");Gt.unescape=un});var Y=C(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.unescape=w.escape=w.Minimatch=w.match=w.braceExpand=w.defaults=w.filter=w.GLOBSTAR=w.sep=w.minimatch=void 0;var fn=vs(),Ls=Ns(),Ut=Ds(),dn=je(),pn=Ne(),mn=(r,t,e={})=>((0,Ut.assertValidPattern)(t),!e.nocomment&&t.charAt(0)==="#"?!1:wn(t,e).match(r));w.minimatch=mn;var ot=new Map,gn=256,wn=(r,t)=>{let e=r+"\0"+JSON.stringify(t),s=ot.get(e);return s?ot.delete(e):(s=new ht(r,{...t}),ot.size>=gn&&ot.delete(ot.keys().next().value)),ot.set(e,s),s},$s=typeof process=="object"&&process?process.env?.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ws={win32:{sep:"\\"},posix:{sep:"/"}};w.sep=$s==="win32"?Ws.win32.sep:Ws.posix.sep;w.minimatch.sep=w.sep;w.GLOBSTAR=Symbol("globstar **");w.minimatch.GLOBSTAR=w.GLOBSTAR;var bn=(r,t={})=>e=>(0,w.minimatch)(e,r,t);w.filter=bn;w.minimatch.filter=w.filter;var q=(r,t={})=>Object.assign({},r,t),yn=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return w.minimatch;let t=w.minimatch;return Object.assign((s,i,n={})=>t(s,i,q(r,n)),{Minimatch:class extends t.Minimatch{constructor(i,n={}){super(i,q(r,n))}static defaults(i){return t.defaults(q(r,i)).Minimatch}},unescape:(s,i={})=>t.unescape(s,q(r,i)),escape:(s,i={})=>t.escape(s,q(r,i)),filter:(s,i={})=>t.filter(s,q(r,i)),defaults:s=>t.defaults(q(r,s)),braceExpand:(s,i={})=>t.braceExpand(s,q(r,i)),match:(s,i,n={})=>t.match(s,i,q(r,n)),sep:t.sep,GLOBSTAR:w.GLOBSTAR})};w.defaults=yn;w.minimatch.defaults=w.defaults;var Sn=(r,t={})=>((0,Ut.assertValidPattern)(r),t.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0,fn.expand)(r,{max:t.braceExpandMax}));w.braceExpand=Sn;w.minimatch.braceExpand=w.braceExpand;var vn=100,_n=/(?{let s=new ht(t,e);return r=r.filter(i=>s.match(i)),s.options.nonull&&!r.length&&r.push(t),r};w.match=En;w.minimatch.match=w.match;var zs=/[?*]|[+@!]\(.*?\)|\[|\]/,Us=(r,t)=>{let e=t+1;(r.charAt(e)==="!"||r.charAt(e)==="^")&&e++;let s=!1;for(;e{if(!t&&(r==="+()"||r==="@()"))return r;let e="";for(let s=0;s{if(/^[?*+@]\(\)$/.test(r)||r.includes("[:"))return!1;let t=0;for(let e=0;etypeof r=="string"?t===r:t!==""&&r.testUnchecked(t),Gs=(r,t,e,s,i)=>V(r,t)?e:s!==void 0&&V(r,s)?i:-1,Be=r=>r==="."||r==="..",Le=r=>typeof r=="string"&&/^[a-z]:$/i.test(r),$t=r=>typeof r=="string"&&/^unc$/i.test(r),We=r=>{if(r[0]!==""||r[1]!=="")return-1;let t=r[2]!=="?"?2:$t(r[3])?4:-1,e=r[t],s=r[t+1];return t!==-1&&e!==void 0&&e!==""&&e!==w.GLOBSTAR&&s!==void 0&&s!==""&&s!==w.GLOBSTAR?t:-1},It=(r,t)=>!Be(r)&&(t||!r.startsWith(".")),pt=(r,t,e,s,i)=>{for(let n=t;n=e||qt(r.charCodeAt(h),i))return!0}let o=Ge(r,n,i);if(o===-1)return!1;for(n=o+1;nt==="/"?r===47:t==="\\"?r===92:r===47||r===92,Ge=(r,t,e)=>{if(e!=="both")return r.indexOf(e,t);let s=r.indexOf("/",t),i=r.indexOf("\\",t);return s===-1?i:i===-1?s:Math.min(s,i)},Is=(r,t,e)=>e!=="both"?r.lastIndexOf(e,t):Math.max(r.lastIndexOf("/",t),r.lastIndexOf("\\",t)),ze={},ht=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;#t;#n;#i;#o;#r=[];#d=[];#f=[];#u=new Map;#h=!1;#m;#l=new WeakMap;constructor(t,e={}){(0,Ut.assertValidPattern)(t),e=e||{},this.options=e,this.maxGlobstarRecursion=e.maxGlobstarRecursion??200,this.pattern=t,this.platform=e.platform||$s,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.#t=!this.preserveMultipleSlashes,this.#i=(e.optimizationLevel??1)>=2;let i=e.normalize;this.#o=i===!0?"NFC":i||void 0,this.make();let n=this.set.map(o=>this.#s(o));this.#f=this.set.map((o,h)=>this.#t&&o.length-1>n[h]),this.#r=this.set.map((o,h)=>{let a=this.#f[h]?o.length-1:o.length,l=o.slice(n[h]+1,a).filter(c=>typeof c=="string"&&!!c);return[...new Set(l)]}),this.#n=this.#r.some(o=>o.length),this.#d=this.set.map((o,h)=>{let[a,l,c]=o;if(this.#f[h]&&o.length===2&&a===w.GLOBSTAR&&l!==w.GLOBSTAR)return"tail";if(this.#f[h]&&e.matchBase&&o.length===1&&a!==w.GLOBSTAR&&a!=="")return"base";if(!(!this.#t||n[h]!==-1)){if(o.length===3&&a===w.GLOBSTAR&&c===w.GLOBSTAR&&l!==w.GLOBSTAR&&l!==""&&this.maxGlobstarRecursion>0)return"mid";if(o.length===2&&l===w.GLOBSTAR&&a!==w.GLOBSTAR&&a!=="")return"head"}})}#a(t){return this.#o?t.normalize(this.#o):t}#s(t){if(!this.isWindows)return-1;if(Le(t[0]))return 0;if(t[0]===""&&t[1]===""&&t[2]==="?"&&Le(t[3]))return 3;let s=We(t);return s===-1?-1:s+1}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.#M())];let s=this.globSet.map(n=>this.#e(n));this.globParts=this.preprocess(s),this.#h=!0;let i=this.globParts.map((n,o,h)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=n[2]==="?"&&$t(n[3])?6:4,l=n[0]===""&&n[1]===""&&(n[2]==="?"||!zs.test(n[2]))&&n.slice(3,a).every(u=>!zs.test(u)),c=/^[a-z]:/i.test(n[0]);if(l)return[...n.slice(0,a).map(u=>this.#a(u)),...n.slice(a).map(u=>this.parse(u))];if(c)return[this.#a(n[0]),...n.slice(1).map(u=>this.parse(u))]}return n.map(a=>this.parse(a))});if(this.set=i.filter(n=>n.indexOf(!1)===-1),this.isWindows)for(let n=0;n{for(let h=0;hs.length));for(let s=0;s{if(!(o[s]instanceof Ls.Matcher||o[s]===ze)||!xn(this.globParts[h][s]))return;let a=[...this.globParts[h]];a[s]="";let l=`${o.length}/${a.join("/")}`,c=i.get(l);c?c.push(h):i.set(l,[h])});let n=new Set;for(let o of i.values()){if(o.length<2)continue;let[h,...a]=o,c=`@(${o.map(u=>this.globParts[u][s]).join("|")})`;this.globParts[h][s]=c,this.set[h][s]=this.parse(c);for(let u of a)n.add(u)}n.size&&(t=!0,this.set=this.set.filter((o,h)=>!n.has(h)),this.globParts=this.globParts.filter((o,h)=>!n.has(h)))}}}preprocess(t){if(this.options.noglobstar)for(let s of t)for(let i=0;i=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>{let s=this.#s(e)+1;return e=e.reduce((i,n)=>{let o=i[i.length-1];return n==="**"&&o==="**"?i:n===".."&&i.length>s&&o&&o!==".."&&o!=="."&&o!=="**"?(i.pop(),i):(i.push(n),i)},[]),e.length===0?[""]:e})}#b(t){let e=!this.isWindows||!t.includes("\\")?"/":t.includes("/")?"both":"\\",s=this.#t?0:-1,i="",n=0,o,h=0,a=!!this.options.dot;t:for(let l=0;l=0){let m=d;for(;m>0&&qt(t.charCodeAt(m-1),e);)m--;h=m===0?0:Is(t,m-1,e)+1,o=t.slice(h,m)}let b=this.#i&&(Be(i)||i===""&&o!==void 0&&Be(o));s=b?-1:1,f=!b}let p=-1;if(f&&typeof u=="string"&&(p=Gs(u,i,n,o,h),p===-1))continue;if(this.#n){for(let d of this.#r[l])if(!t.includes(d))continue t}if(f&&typeof u=="object"&&(p=Gs(u,i,n,o,h),p===-1))continue;let g=this.#d[l];if(g==="base"&&f)return"yes";if(g==="tail"&&f){if(this.#i&&pt(t,0,p,!0,e))return"maybe";if(!pt(t,0,p,a,e))return"yes";continue}if(g==="mid"||g==="head"){let d=this.#y(t,c,g==="head",a,e);if(d!=="no")return d;continue}return"maybe"}return"no"}#E(t,e,s){let i=!!this.options.dot,n=t.length;if(s==="head"){if(n<2||!V(e[0],t[0]))return!1;for(let h=1;hh&&o.testUnchecked(t.slice(h,a)))&&!pt(t,l,t.length,i,n))return"yes";if(s||pt(t,h,l,i,n))return"no";h=l}return"no"}#g(t){let e=De;return e?.f===t&&e.isWindows===this.isWindows&&e.preserveMultipleSlashes===this.preserveMultipleSlashes&&e.normalize===this.#o?e:void 0}#w(t){let{isWindows:e,preserveMultipleSlashes:s}=this,i=this.#e(e?t.split("\\").join("/"):t),n=this.#o;return n&&(i=i.map(o=>o.normalize(n))),De={f:t,isWindows:e,preserveMultipleSlashes:s,normalize:n,parts:i},De}#p(t){let e=[...t],s=!1;do{if(s=!1,!this.preserveMultipleSlashes){for(let o=1;oh&&o.splice(h+1,c-h);let u=o[h+1],f=o[h+2],p=o[h+3];if(u!==".."||!f||f==="."||f===".."||!p||p==="."||p==="..")continue;let g=o.length-1;if(t.length>=e||s+g>i)throw new RangeError("optimizationLevel 2: too many patterns from '**/..'");n=!0,o.splice(h,1);let d=o.slice(0);d[h]="**",s+=g,t.push(d),h--}if(!this.preserveMultipleSlashes){for(let c=1;c{let h=o.join("/");return e.has(h)?!1:(e.add(h),!0)}),i=new Map;for(let o of s){let h=[];for(let a=0;a1e5)return s;let{dot:n}=this.options;return s.filter(o=>{for(let h of i.values()){if(h[h.length-1]>=o.length)continue;let a=[...o],l=!0,c=!1;for(let u of h){let f=o[u];if(f!=="*"){if(!f||f==="**"||!n&&f.startsWith(".")){l=!1;break}a[u]="*",c=!0}}if(l&&c&&e.has(a.join("/")))return!1}return!0})}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,s=0;for(let i=0;it.length)return!1;let u=t.length-a.length;if(this.#S(t,a,s,u,0))c=a.length;else{if(t[t.length-1]!==""||i+a.length===t.length||(u--,!this.#S(t,a,s,u,0)))return!1;c=a.length+1}}if(!h.length){let u=!!c;for(let f=i;f{m[1]=g-d[y]});let b={head:l,body:c,tail:u,segments:f};return i[n]=b,b}#_(t,e,s,i,n,o,h,a,l){let c=e[n];if(!c){if(o)return i>=s||i===s-1&&t[i]==="";for(let g=i;g63743)return this.braceExpand();let s=String.fromCharCode(e),i=!1,n=t.replace(_n,(h,a,l)=>{let c=Number(a),u=Number(l);return!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||Math.abs(c-u)+1=0;l--)a=n[l];for(let l=0;l{"use strict";var Hs=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),kn=Hs(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.tracing=r.metrics=void 0;var t=require("node:diagnostics_channel");r.metrics=(0,t.channel)("lru-cache:metrics"),r.tracing=(0,t.tracingChannel)("lru-cache")}),An=Hs(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defaultPerf=void 0,r.defaultPerf=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date});Object.defineProperty(Xt,"__esModule",{value:!0});Xt.LRUCache=void 0;var O=kn(),Rn=An(),Ie=()=>O.metrics.hasSubscribers||O.tracing.hasSubscribers,Xs=new Set,qs=typeof process=="object"&&process?process:{},Pn=(r,t,e,s)=>{typeof qs.emitWarning=="function"?qs.emitWarning(r,t,e,s):console.error(`[${e}] ${t}: ${r}`)},Tn=r=>!Xs.has(r),J=r=>!!r&&r===Math.floor(r)&&r>0&&isFinite(r),Ks=r=>J(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Ht:null:null,Ht=class extends Array{constructor(r){super(r),this.fill(0)}},Fn=class mt{heap;length;static#t=!1;static create(t){let e=Ks(t);if(!e)return[];mt.#t=!0;let s=new mt(t,e);return mt.#t=!1,s}constructor(t,e){if(!mt.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},jn=class Vs{#t;#n;#i;#o;#r;#d;#f;#u;get perf(){return this.#u}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#h;#m;#l;#a;#s;#b;#E;#y;#g;#w;#p;#O;#x;#v;#_;#S;#M;#e;#P;static unsafeExposeInternals(t){return{starts:t.#x,ttls:t.#v,autopurgeTimers:t.#_,sizes:t.#O,keyMap:t.#l,keyList:t.#a,valList:t.#s,next:t.#b,prev:t.#E,get head(){return t.#y},get tail(){return t.#g},free:t.#w,isBackgroundFetch:e=>t.#c(e),backgroundFetch:(e,s,i,n)=>t.#L(e,s,i,n),moveToTail:e=>t.#K(e),indexes:e=>t.#A(e),rindexes:e=>t.#R(e),isStale:e=>t.#C(e)}}get max(){return this.#t}get maxSize(){return this.#n}get calculatedSize(){return this.#m}get size(){return this.#h}get fetchMethod(){return this.#d}get memoMethod(){return this.#f}get dispose(){return this.#i}get onInsert(){return this.#o}get disposeAfter(){return this.#r}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:h,allowStale:a,dispose:l,onInsert:c,disposeAfter:u,noDisposeOnSet:f,noUpdateTTL:p,maxSize:g=0,maxEntrySize:d=0,sizeCalculation:b,fetchMethod:m,memoMethod:y,noDeleteOnFetchRejection:_,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:S,allowStaleOnFetchAbort:K,ignoreFetchAbort:B,backgroundFetchSize:U=1,perf:rt}=t;if(this.backgroundFetchSize=U,rt!==void 0&&typeof rt?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#u=rt??Rn.defaultPerf,e!==0&&!J(e))throw new TypeError("max option must be a nonnegative integer");let Se=e?Ks(e):Array;if(!Se)throw new Error("invalid max value: "+e);if(this.#t=e,this.#n=g,this.maxEntrySize=d||this.#n,this.sizeCalculation=b,this.sizeCalculation){if(!this.#n&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#f=y,m!==void 0&&typeof m!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#d=m,this.#M=!!m,this.#l=new Map,this.#a=Array.from({length:e}).fill(void 0),this.#s=Array.from({length:e}).fill(void 0),this.#b=new Se(e),this.#E=new Se(e),this.#y=0,this.#g=0,this.#w=Fn.create(e),this.#h=0,this.#m=0,typeof l=="function"&&(this.#i=l),typeof c=="function"&&(this.#o=c),typeof u=="function"?(this.#r=u,this.#p=[]):(this.#r=void 0,this.#p=void 0),this.#S=!!this.#i,this.#P=!!this.#o,this.#e=!!this.#r,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!_,this.allowStaleOnFetchRejection=!!S,this.allowStaleOnFetchAbort=!!K,this.ignoreFetchAbort=!!B,this.maxEntrySize!==0){if(this.#n!==0&&!J(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!J(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#U()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!h,this.ttlResolution=J(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!J(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#T()}if(this.#t===0&&this.ttl===0&&this.#n===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#n){let ve="LRU_CACHE_UNBOUNDED";Tn(ve)&&(Xs.add(ve),Pn("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",ve,Vs))}}getRemainingTTL(t){return this.#l.has(t)?1/0:0}#T(){let t=new Ht(this.#t),e=new Ht(this.#t);this.#v=t,this.#x=e;let s=this.ttlAutopurge?Array.from({length:this.#t}):void 0;this.#_=s,this.#z=(a,l,c=this.#u.now())=>{e[a]=l!==0?c:0,t[a]=l,i(a,l)},this.#k=a=>{e[a]=t[a]!==0?this.#u.now():0,i(a,t[a])};let i=this.ttlAutopurge?(a,l)=>{if(s?.[a]&&(clearTimeout(s[a]),s[a]=void 0),l&&l!==0&&s){let c=setTimeout(()=>{this.#C(a)?(this.#W(this.#a[a],"expire"),s[a]=void 0):i(a,h(a))},l+1);c.unref&&c.unref(),s[a]=c}}:()=>{};this.#F=(a,l)=>{if(t[l]){let c=t[l],u=e[l];if(!c||!u)return;a.ttl=c,a.start=u,a.now=n||o();let f=a.now-u;a.remainingTTL=c-f}};let n=0,o=()=>{let a=this.#u.now();if(this.ttlResolution>0){n=a;let l=setTimeout(()=>n=0,this.ttlResolution);l.unref&&l.unref()}return a};this.getRemainingTTL=a=>{let l=this.#l.get(a);return l===void 0?0:h(l)};let h=a=>{let l=t[a],c=e[a];if(!l||!c)return 1/0;let u=(n||o())-c;return l-u};this.#C=a=>{let l=e[a],c=t[a];return!!c&&!!l&&(n||o())-l>c}}#k=()=>{};#F=()=>{};#z=()=>{};#C=()=>!1;#U(){let t=new Ht(this.#t);this.#m=0,this.#O=t,this.#N=e=>{this.#m-=t[e],t[e]=0},this.#B=(e,s,i,n)=>{if(!J(i)){if(this.#c(s))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,e),!J(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return i},this.#j=(e,s,i)=>{if(t[e]=s,this.#n){let n=this.#n-t[e];for(;this.#m>n;)this.#$(!0)}this.#m+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#m)}}#N=t=>{};#j=(t,e,s)=>{};#B=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#h)for(let e=this.#g;this.#G(e)&&((t||!this.#C(e))&&(yield e),e!==this.#y);)e=this.#E[e]}*#R({allowStale:t=this.allowStale}={}){if(this.#h)for(let e=this.#y;this.#G(e)&&((t||!this.#C(e))&&(yield e),e!==this.#g);)e=this.#b[e]}#G(t){return t!==void 0&&this.#l.get(this.#a[t])===t}*entries(){for(let t of this.#A())this.#s[t]!==void 0&&this.#a[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#a[t],this.#s[t]])}*rentries(){for(let t of this.#R())this.#s[t]!==void 0&&this.#a[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#a[t],this.#s[t]])}*keys(){for(let t of this.#A()){let e=this.#a[t];e!==void 0&&!this.#c(this.#s[t])&&(yield e)}}*rkeys(){for(let t of this.#R()){let e=this.#a[t];e!==void 0&&!this.#c(this.#s[t])&&(yield e)}}*values(){for(let t of this.#A())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}*rvalues(){for(let t of this.#R())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#A()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&t(n,this.#a[s],this))return this.#X(this.#a[s],e)}}forEach(t,e=this){for(let s of this.#A()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(e,n,this.#a[s],this)}}rforEach(t,e=this){for(let s of this.#R()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(e,n,this.#a[s],this)}}purgeStale(){let t=!1;for(let e of this.#R({allowStale:!0}))this.#C(e)&&(this.#W(this.#a[e],"expire"),t=!0);return t}info(t){let e=this.#l.get(t);if(e===void 0)return;let s=this.#s[e],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#v&&this.#x){let o=this.#v[e],h=this.#x[e];if(o&&h){let a=o-(this.#u.now()-h);n.ttl=a,n.start=Date.now()}}return this.#O&&(n.size=this.#O[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let s=this.#a[e],i=this.#s[e],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#v&&this.#x){o.ttl=this.#v[e];let h=this.#u.now()-this.#x[e];o.start=Math.floor(Date.now()-h)}this.#O&&(o.size=this.#O[e]),t.unshift([s,o])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#u.now()-i}this.#D(e,s.value,s)}}set(t,e,s={}){let{status:i=O.metrics.hasSubscribers?{}:void 0}=s;s.status=i,i&&(i.op="set",i.key=t,e!==void 0&&(i.value=e),i.cache=this);let n=this.#D(t,e,s);return i&&O.metrics.hasSubscribers&&O.metrics.publish(i),n}#D(t,e,s,i){let{ttl:n=this.ttl,start:o,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,c=this.#c(e);if(e===void 0)return l&&(l.set="deleted"),this.delete(t),this;let{noUpdateTTL:u=this.noUpdateTTL}=s;l&&!c&&(l.value=e);let f=this.#B(t,e,s.size||0,a,l);if(this.maxEntrySize&&f>this.maxEntrySize)return this.#W(t,"set"),l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this;let p=this.#h===0?void 0:this.#l.get(t);if(p===void 0)p=this.#h===0?this.#g:this.#w.length!==0?this.#w.pop():this.#h===this.#t?this.#$(!1):this.#h,this.#a[p]=t,this.#s[p]=e,this.#l.set(t,p),this.#b[this.#g]=p,this.#E[p]=this.#g,this.#g=p,this.#h++,this.#j(p,f,l),l&&(l.set="add"),u=!1,this.#P&&!c&&this.#o?.(e,t,"add");else{this.#K(p);let g=this.#s[p];if(e!==g){if(!h)if(this.#c(g)){g!==i&&g.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:d}=g;d!==void 0&&d!==e&&(this.#S&&this.#i?.(d,t,"set"),this.#e&&this.#p?.push([d,t,"set"]))}else this.#S&&this.#i?.(g,t,"set"),this.#e&&this.#p?.push([g,t,"set"]);if(this.#N(p),this.#j(p,f,l),this.#s[p]=e,!c){let d=g&&this.#c(g)?g.__staleWhileFetching:g,b=d===void 0?"add":e!==d?"replace":"update";l&&(l.set=b,d!==void 0&&(l.oldValue=d)),this.#P&&this.onInsert?.(e,t,b)}}else c||(l&&(l.set="update"),this.#P&&this.onInsert?.(e,t,"update"))}if(n!==0&&!this.#v&&this.#T(),this.#v&&(u||this.#z(p,n,o),l&&this.#F(l,p)),!h&&this.#e&&this.#p){let g=this.#p,d;for(;d=g?.shift();)this.#r?.(...d)}return this}pop(){try{for(;this.#h;){let t=this.#s[this.#y];if(this.#$(!0),this.#c(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#p){let t=this.#p,e;for(;e=t?.shift();)this.#r?.(...e)}}}#$(t){let e=this.#y,s=this.#a[e],i=this.#s[e],n=this.#c(i);n&&i.__abortController.abort(new Error("evicted"));let o=n?i.__staleWhileFetching:i;return(this.#S||this.#e)&&o!==void 0&&(this.#S&&this.#i?.(o,s,"evict"),this.#e&&this.#p?.push([o,s,"evict"])),this.#N(e),this.#_?.[e]&&(clearTimeout(this.#_[e]),this.#_[e]=void 0),t&&(this.#a[e]=void 0,this.#s[e]=void 0,this.#w.push(e)),this.#h===1?(this.#y=this.#g=0,this.#w.length=0):this.#y=this.#b[e],this.#l.delete(s),this.#h--,e}has(t,e={}){let{status:s=O.metrics.hasSubscribers?{}:void 0}=e;e.status=s,s&&(s.op="has",s.key=t,s.cache=this);let i=this.#V(t,e);return O.metrics.hasSubscribers&&O.metrics.publish(s),i}#V(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,n=this.#l.get(t);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#C(n))i&&(i.has="stale",this.#F(i,n));else return s&&this.#k(n),i&&(i.has="hit",this.#F(i,n)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{status:s=Ie()?{}:void 0}=e;s&&(s.op="peek",s.key=t,s.cache=this),e.status=s;let i=this.#q(t,e);return O.metrics.hasSubscribers&&O.metrics.publish(s),i}#q(t,e){let{status:s,allowStale:i=this.allowStale}=e,n=this.#l.get(t);if(n===void 0||!i&&this.#C(n)){s&&(s.peek=n===void 0?"miss":"stale");return}let o=this.#s[n],h=this.#c(o)?o.__staleWhileFetching:o;return s&&(h!==void 0?(s.peek="hit",s.value=h):s.peek="miss"),h}#L(t,e,s,i){let n=e===void 0?void 0:this.#s[e];if(this.#c(n))return n;let o=new AbortController,{signal:h}=s;h?.addEventListener("abort",()=>o.abort(h.reason),{signal:o.signal});let a={signal:o.signal,options:s,context:i},l=(d,b=!1)=>{let{aborted:m}=o.signal,y=s.ignoreFetchAbort&&d!==void 0,_=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&d!==void 0);if(s.status&&(m&&!b?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,y&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),m&&!y&&!b)return u(o.signal.reason,_);let v=p,S=this.#s[e];return(S===p||S===void 0&&y&&b)&&(d===void 0?v.__staleWhileFetching!==void 0?this.#s[e]=v.__staleWhileFetching:this.#W(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.#D(t,d,a.options,v))),d},c=d=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=d),u(d,!1)),u=(d,b)=>{let{aborted:m}=o.signal,y=m&&s.allowStaleOnFetchAbort,_=y||s.allowStaleOnFetchRejection,v=_||s.noDeleteOnFetchRejection,S=p;if(this.#s[e]===p&&(!v||!b&&S.__staleWhileFetching===void 0?this.#W(t,"fetch"):y||(this.#s[e]=S.__staleWhileFetching)),_)return s.status&&S.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),S.__staleWhileFetching;if(S.__returned===S)throw d},f=(d,b)=>{let m=this.#d?.(t,n,a);o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(d(void 0),s.allowStaleOnFetchAbort&&(d=y=>l(y,!0)))}),m&&m instanceof Promise?m.then(y=>d(y===void 0?void 0:y),b):m!==void 0&&d(m)};s.status&&(s.status.fetchDispatched=!0);let p=new Promise(f).then(l,c),g=Object.assign(p,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#D(t,g,{...a.options,status:void 0}),e=this.#l.get(t)):this.#s[e]=g,g}#c(t){if(!this.#M)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof AbortController}fetch(t,e={}){let s=O.tracing.hasSubscribers,{status:i=Ie()?{}:void 0}=e;e.status=i,i&&e.context&&(i.context=e.context);let n=this.#H(t,e);return i&&s&&(i.trace=!0,O.tracing.tracePromise(()=>n,i).catch(()=>{})),n}async#H(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:d,forceRefresh:b=!1,status:m,signal:y}=e;if(m&&(m.op="fetch",m.key=t,b&&(m.forceRefresh=!0),m.cache=this),!this.#M)return m&&(m.fetch="get"),this.#X(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:m});let _={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:h,size:a,sizeCalculation:l,noUpdateTTL:c,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:g,ignoreFetchAbort:p,status:m,signal:y},v=this.#l.get(t);if(v===void 0){m&&(m.fetch="miss");let S=this.#L(t,v,_,d);return S.__returned=S}else{let S=this.#s[v];if(this.#c(S)){let rt=s&&S.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",rt&&(m.returnedStale=!0)),rt?S.__staleWhileFetching:S.__returned=S}let K=this.#C(v);if(!b&&!K)return m&&(m.fetch="hit"),this.#K(v),i&&this.#k(v),m&&this.#F(m,v),S;let B=this.#L(t,v,_,d),U=B.__staleWhileFetching!==void 0&&s;return m&&(m.fetch=K?"stale":"refresh",U&&K&&(m.returnedStale=!0)),U?B.__staleWhileFetching:B.__returned=B}}forceFetch(t,e={}){let s=O.tracing.hasSubscribers,{status:i=Ie()?{}:void 0}=e;e.status=i,i&&e.context&&(i.context=e.context);let n=this.#I(t,e);return i&&s&&(i.trace=!0,O.tracing.tracePromise(()=>n,i).catch(()=>{})),n}async#I(t,e={}){let s=await this.#H(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let{status:s=O.metrics.hasSubscribers?{}:void 0}=e;e.status=s,s&&(s.op="memo",s.key=t,e.context&&(s.context=e.context),s.cache=this);let i=this.#Z(t,e);return s&&(s.value=i),O.metrics.hasSubscribers&&O.metrics.publish(s),i}#Z(t,e={}){let s=this.#f;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,status:n,forceRefresh:o,...h}=e;n&&o&&(n.forceRefresh=!0);let a=this.#X(t,h),l=o||a===void 0;if(n&&(n.memo=l?"miss":"hit",l||(n.value=a)),!l)return a;let c=s(t,a,{options:h,context:i});return n&&(n.value=c),this.#D(t,c,h),c}get(t,e={}){let{status:s=O.metrics.hasSubscribers?{}:void 0}=e;e.status=s,s&&(s.op="get",s.key=t,s.cache=this);let i=this.#X(t,e);return s&&(i!==void 0&&(s.value=i),O.metrics.hasSubscribers&&O.metrics.publish(s)),i}#X(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=e,h=this.#l.get(t);if(h===void 0){o&&(o.get="miss");return}let a=this.#s[h],l=this.#c(a);return o&&this.#F(o,h),this.#C(h)?l?(o&&(o.get="stale-fetching"),s&&a.__staleWhileFetching!==void 0?(o&&(o.returnedStale=!0),a.__staleWhileFetching):void 0):(n||this.#W(t,"expire"),o&&(o.get="stale"),s?(o&&(o.returnedStale=!0),a):void 0):(o&&(o.get=l?"fetching":"hit"),this.#K(h),i&&this.#k(h),l?a.__staleWhileFetching:a)}#Y(t,e){this.#E[e]=t,this.#b[t]=e}#K(t){t!==this.#g&&(t===this.#y?this.#y=this.#b[t]:this.#Y(this.#E[t],this.#b[t]),this.#Y(this.#g,t),this.#g=t)}delete(t){return this.#W(t,"delete")}#W(t,e){O.metrics.hasSubscribers&&O.metrics.publish({op:"delete",delete:e,key:t,cache:this});let s=!1;if(this.#h!==0){let i=this.#l.get(t);if(i!==void 0)if(this.#_?.[i]&&(clearTimeout(this.#_[i]),this.#_[i]=void 0),s=!0,this.#h===1)this.#J(e);else{this.#N(i);let n=this.#s[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#S||this.#e)&&(this.#S&&this.#i?.(n,t,e),this.#e&&this.#p?.push([n,t,e])),this.#l.delete(t),this.#a[i]=void 0,this.#s[i]=void 0,i===this.#g)this.#g=this.#E[i];else if(i===this.#y)this.#y=this.#b[i];else{let o=this.#E[i];this.#b[o]=this.#b[i];let h=this.#b[i];this.#E[h]=this.#E[i]}this.#h--,this.#w.push(i)}}if(this.#e&&this.#p?.length){let i=this.#p,n;for(;n=i?.shift();)this.#r?.(...n)}return s}clear(){return this.#J("delete")}#J(t){for(let e of this.#R({allowStale:!0})){let s=this.#s[e];if(this.#c(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#a[e];this.#S&&this.#i?.(s,i,t),this.#e&&this.#p?.push([s,i,t])}}if(this.#l.clear(),this.#s.fill(void 0),this.#a.fill(void 0),this.#v&&this.#x){this.#v.fill(0),this.#x.fill(0);for(let e of this.#_??[])e!==void 0&&clearTimeout(e);this.#_?.fill(void 0)}if(this.#O&&this.#O.fill(0),this.#y=0,this.#g=0,this.#w.length=0,this.#m=0,this.#h=0,this.#e&&this.#p){let e=this.#p,s;for(;s=e?.shift();)this.#r?.(...s)}}};Xt.LRUCache=jn});var Ye=C(j=>{"use strict";var Nn=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(j,"__esModule",{value:!0});j.Minipass=j.isWritable=j.isReadable=j.isStream=void 0;var Js=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ve=require("node:events"),ei=Nn(require("node:stream")),Dn=require("node:string_decoder"),Ln=r=>!!r&&typeof r=="object"&&(r instanceof te||r instanceof ei.default||(0,j.isReadable)(r)||(0,j.isWritable)(r));j.isStream=Ln;var Wn=r=>!!r&&typeof r=="object"&&r instanceof Ve.EventEmitter&&typeof r.pipe=="function"&&r.pipe!==ei.default.Writable.prototype.pipe;j.isReadable=Wn;var zn=r=>!!r&&typeof r=="object"&&r instanceof Ve.EventEmitter&&typeof r.write=="function"&&typeof r.end=="function";j.isWritable=zn;var H=Symbol("EOF"),X=Symbol("maybeEmitEnd"),Z=Symbol("emittedEnd"),Kt=Symbol("emittingEnd"),gt=Symbol("emittedError"),Vt=Symbol("closed"),Zs=Symbol("read"),Yt=Symbol("flush"),Qs=Symbol("flushChunk"),W=Symbol("encoding"),at=Symbol("decoder"),M=Symbol("flowing"),wt=Symbol("paused"),lt=Symbol("resume"),k=Symbol("buffer"),F=Symbol("pipes"),A=Symbol("bufferLength"),$e=Symbol("bufferPush"),Jt=Symbol("bufferShift"),P=Symbol("objectMode"),x=Symbol("destroyed"),Ue=Symbol("error"),qe=Symbol("emitData"),ti=Symbol("emitEnd"),He=Symbol("emitEnd2"),G=Symbol("async"),Xe=Symbol("abort"),Zt=Symbol("aborted"),bt=Symbol("signal"),st=Symbol("dataListeners"),N=Symbol("discarded"),yt=r=>Promise.resolve().then(r),Bn=r=>r(),Gn=r=>r==="end"||r==="finish"||r==="prefinish",In=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,$n=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),Qt=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[lt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ke=class extends Qt{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},Un=r=>!!r.objectMode,qn=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",te=class extends Ve.EventEmitter{[M]=!1;[wt]=!1;[F]=[];[k]=[];[P];[W];[G];[at];[H]=!1;[Z]=!1;[Kt]=!1;[Vt]=!1;[gt]=null;[A]=0;[x]=!1;[bt];[Zt]=!1;[st]=0;[N]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Un(e)?(this[P]=!0,this[W]=null):qn(e)?(this[W]=e.encoding,this[P]=!1):(this[P]=!1,this[W]=null),this[G]=!!e.async,this[at]=this[W]?new Dn.StringDecoder(this[W]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[k]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[F]});let{signal:s}=e;s&&(this[bt]=s,s.aborted?this[Xe]():s.addEventListener("abort",()=>this[Xe]()))}get bufferLength(){return this[A]}get encoding(){return this[W]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[P]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[G]}set async(t){this[G]=this[G]||!!t}[Xe](){this[Zt]=!0,this.emit("abort",this[bt]?.reason),this.destroy(this[bt]?.reason)}get aborted(){return this[Zt]}set aborted(t){}write(t,e,s){if(this[Zt])return!1;if(this[H])throw new Error("write after end");if(this[x])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[G]?yt:Bn;if(!this[P]&&!Buffer.isBuffer(t)){if($n(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(In(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[P]?(this[M]&&this[A]!==0&&this[Yt](!0),this[M]?this.emit("data",t):this[$e](t),this[A]!==0&&this.emit("readable"),s&&i(s),this[M]):t.length?(typeof t=="string"&&!(e===this[W]&&!this[at]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[W]&&(t=this[at].write(t)),this[M]&&this[A]!==0&&this[Yt](!0),this[M]?this.emit("data",t):this[$e](t),this[A]!==0&&this.emit("readable"),s&&i(s),this[M]):(this[A]!==0&&this.emit("readable"),s&&i(s),this[M])}read(t){if(this[x])return null;if(this[N]=!1,this[A]===0||t===0||t&&t>this[A])return this[X](),null;this[P]&&(t=null),this[k].length>1&&!this[P]&&(this[k]=[this[W]?this[k].join(""):Buffer.concat(this[k],this[A])]);let e=this[Zs](t||null,this[k][0]);return this[X](),e}[Zs](t,e){if(this[P])this[Jt]();else{let s=e;t===s.length||t===null?this[Jt]():typeof s=="string"?(this[k][0]=s.slice(t),e=s.slice(0,t),this[A]-=t):(this[k][0]=s.subarray(t),e=s.subarray(0,t),this[A]-=t)}return this.emit("data",e),!this[k].length&&!this[H]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[H]=!0,this.writable=!1,(this[M]||!this[wt])&&this[X](),this}[lt](){this[x]||(!this[st]&&!this[F].length&&(this[N]=!0),this[wt]=!1,this[M]=!0,this.emit("resume"),this[k].length?this[Yt]():this[H]?this[X]():this.emit("drain"))}resume(){return this[lt]()}pause(){this[M]=!1,this[wt]=!0,this[N]=!1}get destroyed(){return this[x]}get flowing(){return this[M]}get paused(){return this[wt]}[$e](t){this[P]?this[A]+=1:this[A]+=t.length,this[k].push(t)}[Jt](){return this[P]?this[A]-=1:this[A]-=this[k][0].length,this[k].shift()}[Yt](t=!1){do;while(this[Qs](this[Jt]())&&this[k].length);!t&&!this[k].length&&!this[H]&&this.emit("drain")}[Qs](t){return this.emit("data",t),this[M]}pipe(t,e){if(this[x])return t;this[N]=!1;let s=this[Z];return e=e||{},t===Js.stdout||t===Js.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[F].push(e.proxyErrors?new Ke(this,t,e):new Qt(this,t,e)),this[G]?yt(()=>this[lt]()):this[lt]()),t}unpipe(t){let e=this[F].find(s=>s.dest===t);e&&(this[F].length===1?(this[M]&&this[st]===0&&(this[M]=!1),this[F]=[]):this[F].splice(this[F].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[N]=!1,this[st]++,!this[F].length&&!this[M]&&this[lt]();else if(t==="readable"&&this[A]!==0)super.emit("readable");else if(Gn(t)&&this[Z])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[gt]){let i=e;this[G]?yt(()=>i.call(this,this[gt])):i.call(this,this[gt])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[st]=this.listeners("data").length,this[st]===0&&!this[N]&&!this[F].length&&(this[M]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[st]=0,!this[N]&&!this[F].length&&(this[M]=!1)),e}get emittedEnd(){return this[Z]}[X](){!this[Kt]&&!this[Z]&&!this[x]&&this[k].length===0&&this[H]&&(this[Kt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Vt]&&this.emit("close"),this[Kt]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==x&&this[x])return!1;if(t==="data")return!this[P]&&!s?!1:this[G]?(yt(()=>this[qe](s)),!0):this[qe](s);if(t==="end")return this[ti]();if(t==="close"){if(this[Vt]=!0,!this[Z]&&!this[x])return!1;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[gt]=s,super.emit(Ue,s);let n=!this[bt]||this.listeners("error").length?super.emit("error",s):!1;return this[X](),n}else if(t==="resume"){let n=super.emit("resume");return this[X](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let i=super.emit(t,...e);return this[X](),i}[qe](t){for(let s of this[F])s.dest.write(t)===!1&&this.pause();let e=this[N]?!1:super.emit("data",t);return this[X](),e}[ti](){return this[Z]?!1:(this[Z]=!0,this.readable=!1,this[G]?(yt(()=>this[He]()),!0):this[He]())}[He](){if(this[at]){let e=this[at].end();if(e){for(let s of this[F])s.dest.write(e);this[N]||super.emit("data",e)}}for(let e of this[F])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[P]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[P]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[P])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[W]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(x,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[N]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[H])return e();let n,o,h=u=>{this.off("data",a),this.off("end",l),this.off(x,c),e(),o(u)},a=u=>{this.off("error",h),this.off("end",l),this.off(x,c),this.pause(),n({value:u,done:!!this[H]})},l=()=>{this.off("error",h),this.off("data",a),this.off(x,c),e(),n({done:!0,value:void 0})},c=()=>h(new Error("stream destroyed"));return new Promise((u,f)=>{o=f,n=u,this.once(x,c),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[N]=!1;let t=!1,e=()=>(this.pause(),this.off(Ue,e),this.off(x,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Ue,e),this.once(x,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[x])return t?this.emit("error",t):this.emit(x),this;this[x]=!0,this[N]=!0,this[k].length=0,this[A]=0;let e=this;return typeof e.close=="function"&&!this[Vt]&&e.close(),t?this.emit("error",t):this.emit(x),this}static get isStream(){return j.isStream}};j.Minipass=te});var mi=C(E=>{"use strict";var Hn=E&&E.__createBinding||(Object.create?(function(r,t,e,s){s===void 0&&(s=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(r,s,i)}):(function(r,t,e,s){s===void 0&&(s=e),r[s]=t[e]})),Xn=E&&E.__setModuleDefault||(Object.create?(function(r,t){Object.defineProperty(r,"default",{enumerable:!0,value:t})}):function(r,t){r.default=t}),Kn=E&&E.__importStar||(function(){var r=function(t){return r=Object.getOwnPropertyNames||function(e){var s=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(s[s.length]=i);return s},r(t)};return function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var s=r(t),i=0;i!r||r===_t||r===Yn?_t:{..._t,...r,promises:{..._t.promises,...r.promises}},Zn=/^\\\\\?\\([a-z]:)\\?$/i,Qn=/^\\\\\?\\UNC\\([^\\]+\\[^\\]+)\\?$/i,tr=/^\\\\[^\\?]+\\[^\\]+$/,ii=r=>r.replace(/\//g,"\\").replace(Zn,"$1\\").replace(Qn,"\\\\$1\\").replace(tr,"$&\\"),er=/^[\\/]{2}\?[\\/]unc[\\/][^\\/]+[\\/][^\\/]+(?:[\\/]|$)/i,sr=/^[\\/]{2}\?[\\/](?=[a-z]:)/i,ir=/^[\\/]{2}\?[\\/]unc(?=[\\/][^\\/]+[\\/][^\\/])/i,nr=/[\\/]/,L=0,li=1,ci=2,I=4,ui=6,fi=8,it=10,di=12,D=15,St=~D,Je=16,ni=32,Et=64,z=128,se=256,ne=512,ri=Et|z|ne,rr=1023,Ze=r=>r.isFile()?fi:r.isDirectory()?I:r.isSymbolicLink()?it:r.isCharacterDevice()?ci:r.isBlockDevice()?ui:r.isSocket()?di:r.isFIFO()?li:L,oi=new ae.LRUCache({max:2**12}),Ot=r=>{let t=oi.get(r);if(t)return t;let e=r.normalize("NFKD");return oi.set(r,e),e},hi=new ae.LRUCache({max:2**12}),ie=r=>{let t=hi.get(r);if(t)return t;let e=Ot(r.toLowerCase());return hi.set(r,e),e},xt=class extends ae.LRUCache{constructor(){super({max:256})}};E.ResolveCache=xt;var oe=class extends ae.LRUCache{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}};E.ChildrenCache=oe;var pi=Symbol("PathScurry setAsCwd"),R=class{name;root;roots;parent;nocase;isCWD=!1;#t;#n;get dev(){return this.#n}#i;get mode(){return this.#i}#o;get nlink(){return this.#o}#r;get uid(){return this.#r}#d;get gid(){return this.#d}#f;get rdev(){return this.#f}#u;get blksize(){return this.#u}#h;get ino(){return this.#h}#m;get size(){return this.#m}#l;get blocks(){return this.#l}#a;get atimeMs(){return this.#a}#s;get mtimeMs(){return this.#s}#b;get ctimeMs(){return this.#b}#E;get birthtimeMs(){return this.#E}#y;get atime(){return this.#y}#g;get mtime(){return this.#g}#w;get ctime(){return this.#w}#p;get birthtime(){return this.#p}#O;#x;#v;#_;#S;#M;#e;#P;#T;#k;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=L,s,i,n,o,h){this.name=t,this.#O=n?ie(t):Ot(t),this.#e=e&rr,this.nocase=n,this.roots=i,this.root=s||this,this.#P=o,this.#v=h.fullpath,this.#S=h.relative,this.#M=h.relativePosix,this.parent=h.parent,this.parent?this.#t=this.parent.#t:this.#t=ai(h.fs)}get fs(){return this.#t}depth(){return this.#x!==void 0?this.#x:this.parent?this.#x=this.parent.depth()+1:this.#x=0}childrenCache(){return this.#P}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#F(i):this.#F(i)}#F(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#P.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#P.set(this,e),this.#e&=~Je,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?ie(t):Ot(t);for(let a of s)if(a.#O===i)return a;let n=this.parent?this.sep:"",o=this.#v?this.#v+n+t:void 0,h=this.newChild(t,L,{...e,parent:this,fullpath:o});return this.canReaddir()||(h.#e|=z),s.push(h),h}relative(){if(this.isCWD)return"";if(this.#S!==void 0)return this.#S;let t=this.name,e=this.parent;if(!e)return this.#S=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#M!==void 0)return this.#M;let t=this.name,e=this.parent;if(!e)return this.#M=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#v!==void 0)return this.#v;let t=this.name,e=this.parent;if(!e)return this.#v=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#v=i}fullpathPosix(){if(this.#_!==void 0)return this.#_;if(this.sep==="/")return this.#_=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#_=`//?/${i}`:this.#_=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#_=s}isUnknown(){return(this.#e&D)===L}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&D)===fi}isDirectory(){return(this.#e&D)===I}isCharacterDevice(){return(this.#e&D)===ci}isBlockDevice(){return(this.#e&D)===ui}isFIFO(){return(this.#e&D)===li}isSocket(){return(this.#e&D)===di}isSymbolicLink(){return(this.#e&it)===it}lstatCached(){return this.#e&ni?this:void 0}readlinkCached(){return this.#T}realpathCached(){return this.#k}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#T)return!0;if(!this.parent)return!1;let t=this.#e&D;return!(t!==L&&t!==it||this.#e&se||this.#e&z)}calledReaddir(){return!!(this.#e&Je)}isENOENT(){return!!(this.#e&z)}isNamed(t){return this.nocase?this.#O===ie(t):this.#O===Ot(t)}async readlink(){let t=this.#T;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#T=s}catch(e){this.#R(e.code);return}}readlinkSync(){let t=this.#T;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#T=s}catch(e){this.#R(e.code);return}}#z(t){this.#e|=Je;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let n=s.slice(0,s.provisional);e?t(null,n):queueMicrotask(()=>t(null,n));return}if(this.#L.push(t),this.#c)return;this.#c=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(n,o)=>{if(n)this.#B(n.code),s.provisional=0;else{for(let h of o)this.#G(h,s);this.#z(s)}this.#H(s.slice(0,s.provisional))})}#I;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#I)await this.#I;else{let s=()=>{};this.#I=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#G(i,t);this.#z(t)}catch(i){this.#B(i.code),t.provisional=0}this.#I=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#G(s,t);this.#z(t)}catch(s){this.#B(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&ri)return!1;let t=D&this.#e;return t===L||t===I||t===it}shouldWalk(t,e){return(this.#e&I)===I&&!(this.#e&ri)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#k)return this.#k;if(!((ne|se|z)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#k=this.resolve(t)}catch{this.#N()}}realpathSync(){if(this.#k)return this.#k;if(!((ne|se|z)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#k=this.resolve(t)}catch{this.#N()}}[pi](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#S=s.join(this.sep),i.#M=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#S=void 0,i.#M=void 0,i=i.parent}};E.PathBase=R;var Ct=class r extends R{sep="\\";splitSep=nr;constructor(t,e=L,s,i,n,o,h){super(t,e,s,i,n,o,h)}newChild(t,e=L,s={}){return new r(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return er.exec(t)?.[0]??re.win32.parse(t).root}getRoot(t){if(t=ii(t.toUpperCase()),t===this.root.name||/^[\\/]$/.test(t))return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new At(t,{nocase:this.nocase,fs:this.fs}).root}sameRoot(t,e=this.root.name){return ii(t.toUpperCase())===e}};E.PathWin32=Ct;var Mt=class r extends R{splitSep="/";sep="/";constructor(t,e=L,s,i,n,o,h){super(t,e,s,i,n,o,h)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=L,s={}){return new r(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}};E.PathPosix=Mt;var kt=class{root;rootPath;roots;cwd;#t;#n;#i;nocase;#o;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:n=16*1024,fs:o=_t}={}){this.#o=ai(o),(t instanceof URL||t.startsWith("file://"))&&(t=(0,Vn.fileURLToPath)(t));let h=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(h),this.#t=new xt,this.#n=new xt,this.#i=new oe(n);let a=h.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#o),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=e.sep,f=this.rootPath,p=!1;for(let g of a){let d=c--;l=l.child(g,{relative:new Array(d).fill("..").join(u),relativePosix:new Array(d).fill("..").join("/"),fullpath:f+=(p?"":u)+g}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#i}resolve(...t){let e="";for(let n=t.length-1;n>=0;n--){let o=t[n];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let n=t.length-1;n>=0;n--){let o=t[n];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#n.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#n.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(n=>n.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,h=[];(!n||n(t))&&h.push(s?t:t.fullpath());let a=new Set,l=(u,f)=>{a.add(u),u.readdirCB((p,g)=>{if(p)return f(p);let d=g.length;if(!d)return f();let b=()=>{--d===0&&f()};for(let m of g)(!n||n(m))&&h.push(s?m:m.fullpath()),i&&m.isSymbolicLink()?m.realpath().then(y=>y?.isUnknown()?y.lstat():y).then(y=>y?.shouldWalk(a,o)?l(y,b):b()):m.shouldWalk(a,o)?l(m,b):b()},!0)},c=t;return new Promise((u,f)=>{l(c,p=>{if(p)return f(p);u(h)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,h=[];(!n||n(t))&&h.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let u of c){(!n||n(u))&&h.push(s?u:u.fullpath());let f=u;if(u.isSymbolicLink()){if(!(i&&(f=u.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(a,o)&&a.add(f)}}return h}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e;(!n||n(t))&&(yield s?t:t.fullpath());let h=new Set([t]);for(let a of h){let l=a.readdirSync();for(let c of l){(!n||n(c))&&(yield s?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(i&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(h,o)&&h.add(u)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,h=new si.Minipass({objectMode:!0});(!n||n(t))&&h.write(s?t:t.fullpath());let a=new Set,l=[t],c=0,u=()=>{let f=!1;for(;!f;){let p=l.shift();if(!p){c===0&&h.end();return}c++,a.add(p);let g=(b,m,y=!1)=>{if(b)return h.emit("error",b);if(i&&!y){let _=[];for(let v of m)v.isSymbolicLink()&&_.push(v.realpath().then(S=>S?.isUnknown()?S.lstat():S));if(_.length){Promise.all(_).then(()=>g(null,m,!0));return}}for(let _ of m)_&&(!n||n(_))&&(h.write(s?_:_.fullpath())||(f=!0));c--;for(let _ of m){let v=_.realpathCached()||_;v.shouldWalk(a,o)&&l.push(v)}f&&!h.flowing?h.once("drain",u):d||u()},d=!0;p.readdirCB(g,!0),d=!1}};return u(),h}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,h=new si.Minipass({objectMode:!0}),a=new Set;(!n||n(t))&&h.write(s?t:t.fullpath());let l=[t],c=0,u=()=>{let f=!1;for(;!f;){let p=l.shift();if(!p){c===0&&h.end();return}c++,a.add(p);let g=p.readdirSync();for(let d of g)(!n||n(d))&&(h.write(s?d:d.fullpath())||(f=!0));c--;for(let d of g){let b=d;if(d.isSymbolicLink()){if(!(i&&(b=d.realpathSync())))continue;b.isUnknown()&&b.lstatSync()}b.shouldWalk(a,o)&&l.push(b)}}f&&!h.flowing&&h.once("drain",u)};return u(),h}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[pi](e)}};E.PathScurryBase=kt;var At=class extends kt{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;typeof t=="string"&&!t.startsWith("file://")&&(t=t.replace(sr,"").replace(ir,"\\")),super(t,re.win32,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return re.win32.parse(t).root.toUpperCase()}newRoot(t){return new Ct(this.rootPath,I,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}};E.PathScurryWin32=At;var Rt=class extends kt{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,re.posix,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new Mt(this.rootPath,I,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}};E.PathScurryPosix=Rt;var he=class extends Rt{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}};E.PathScurryDarwin=he;E.Path=process.platform==="win32"?Ct:Mt;E.PathScurry=process.platform==="win32"?At:process.platform==="darwin"?he:Rt});var ts=C(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.Pattern=void 0;var or=Y(),hr=r=>r.length>=1,ar=r=>r.length>=1,lr=Symbol.for("nodejs.util.inspect.custom"),Qe=class r{#t;#n;#i;length;#o;#r;#d;#f;#u;#h;#m=!0;constructor(t,e,s,i){if(!hr(t))throw new TypeError("empty pattern list");if(!ar(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#n=e,this.#i=s,this.#o=i,this.#i===0){if(this.isUNC()){let n=this.#l()?6:4,o=this.#t.slice(0,n),h=this.#n.slice(0,n),a=this.#t.slice(n),l=this.#n.slice(n);a[0]===""&&(a.shift(),l.shift());let c=[...o,""].join("/"),u=[...h,""].join("/");this.#t=[c,...a],this.#n=[u,...l],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#t,[h,...a]=this.#n;o[0]===""&&(o.shift(),a.shift());let l=`${n}/`,c=`${h}/`;this.#t=[l,...o],this.#n=[c,...a],this.length=this.#t.length}}}[lr](){return`Pattern <${this.#n.slice(this.#i).join("/")}>`}pattern(){return this.#t[this.#i]}isString(){return typeof this.#t[this.#i]=="string"}isGlobstar(){return this.#t[this.#i]===or.GLOBSTAR}isMatcher(){return typeof this.#t[this.#i]=="object"}globString(){return this.#d=this.#d||(this.#i===0?this.isAbsolute()?this.#n[0]+this.#n.slice(1).join("/"):this.#n.join("/"):this.#n.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#r!==void 0?this.#r:this.hasMore()?(this.#r=new r(this.#t,this.#n,this.#i+1,this.#o),this.#r.#h=this.#h,this.#r.#u=this.#u,this.#r.#f=this.#f,this.#r):this.#r=null}#l(){let t=this.#t;return t[2]==="?"&&typeof t[3]=="string"&&/^unc$/i.test(t[3])}isUNC(){let t=this.#t,e=this.#l()?4:2;return this.#u!==void 0?this.#u:this.#u=this.#o==="win32"&&this.#i===0&&t[0]===""&&t[1]===""&&typeof t[e]=="string"&&!!t[e]&&typeof t[e+1]=="string"&&!!t[e+1]}isDrive(){let t=this.#t;return this.#f!==void 0?this.#f:this.#f=this.#o==="win32"&&this.#i===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#i===0?t:""}checkFollowGlobstar(){return!(this.#i===0||!this.isGlobstar()||!this.#m)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#m?!1:(this.#m=!1,!0)}};le.Pattern=Qe});var is=C(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.Ignore=void 0;var es=Y(),cr=ts(),ur=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ss=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;slashRoot;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:n,normalize:o,platform:h=ur,root:a,windowsPathsNoEscape:l,allowWindowsEscape:c,braceExpandMax:u=1e4},f){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=h,l=!!l||c===!1,this.mmopts={braceExpandMax:u,dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:n,normalize:o,optimizationLevel:2,platform:h,nocomment:!0,nonegate:!0,windowsPathsNoEscape:l};let p=f?.resolve(a??"/").fullpath()??"/";this.slashRoot=(0,es.escape)(p.replace(/\\/g,"/").replace(/\/$/,""),{magicalBraces:!0,windowsPathsNoEscape:l});for(let g of t)this.add(g)}add(t){let e=new es.Minimatch(t,this.mmopts);for(let s=0;s{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.Processor=$.SubWalks=$.MatchRecord=$.HasWalkedCache=void 0;var gi=Y(),ue=class r{parent;store;constructor(t){this.parent=t}copy(){return new r(this)}#t(t){let e=this.store?.get(t);return e||!this.parent?e:this.parent.#t(t)}hasWalked(t,e){return!!this.#t(t.fullpath())?.has(e.globString())}storeWalked(t,e){let s=t.fullpath(),i=this.#t(s);i?i.add(e.globString()):(this.store??=new Map).set(s,new Set([e.globString()]))}};$.HasWalkedCache=ue;var fe=class r{static ABSOLUTE=2;static IF_DIR=1;store=new Map;add(t,e,s){let i=(e?r.ABSOLUTE:0)|(s?r.IF_DIR:0),n=this.store.get(t);this.store.set(t,n===void 0?i:i&n)}};$.MatchRecord=fe;var de=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}};$.SubWalks=de;var ns=class r{hasWalkedCache;matches=new fe;subwalks=new de;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new ue}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),h=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let u=n.rest();if(u)n=u;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let a,l,c=!1;for(;typeof(a=n.pattern())=="string"&&(l=n.rest());)i=i.resolve(a),n=l,c=!0;if(a=n.pattern(),l=n.rest(),c){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof a=="string"){let u=a===".."||a===""||a===".";this.matches.add(i.resolve(a),h,u);continue}else if(a===gi.GLOBSTAR){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let u=l?.pattern(),f=l?.rest();if(!l||(u===""||u===".")&&!f)this.matches.add(i,h,u===""||u===".");else if(u===".."){let p=i.parent||i;f?this.hasWalkedCache.hasWalked(p,f)||this.subwalks.add(p,f):this.matches.add(p,h,!0)}}else typeof a=="object"&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let n of e)for(let o of s){let h=o.isAbsolute(),a=o.pattern(),l=o.rest();a===gi.GLOBSTAR?i.testGlobstar(n,o,l,h):typeof a=="object"?i.testMatcher(n,a,l,h):i.testString(n,a,l,h)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),i);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s)}else typeof n=="object"&&this.testMatcher(t,n,s.rest(),i)}}testMatcher(t,e,s,i){e.testUnchecked(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};$.Processor=ns});var yi=C(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.GlobStream=Q.GlobWalker=Q.GlobUtil=void 0;var fr=Ye(),bi=is(),rs=wi(),{ABSOLUTE:pe,IF_DIR:me}=rs.MatchRecord,dr=(r,t,e)=>typeof r=="string"?new bi.Ignore([r],t,e):Array.isArray(r)?new bi.Ignore(r,t,e):r,Pt=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#n;#i;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#i=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#n=dr(s.ignore??[],s,e),!this.includeChildMatches&&typeof this.#n.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#o(t){return this.seen.has(t)||!!this.#n?.ignored?.(t)}#r(t){return!!this.#n?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.paused?this.#t.push(t):t()}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s,i;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;i=s}else i=t;let o=i.isUnknown()||this.opts.stat?await i.lstat():i;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let h=await o.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat()}return this.matchCheckTest(o,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#o(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s,i;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;i=s}else i=t;let o=i.isUnknown()||this.opts.stat?i.lstatSync():i;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let h=o.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync()}return this.matchCheckTest(o,e)}matchFinish(t,e){this.#o(t)||this.#d(t,e)}#d(t,e){if(!this.includeChildMatches&&this.#n?.add){let n=`${t.relativePosix()}/**`;this.#n.add(n)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let n=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(n+i)}else{let n=this.opts.posix?t.relativePosix():t.relative(),o=this.opts.dotRelative&&!n.startsWith(`..${this.#i}`)?`.${this.#i}`:"";this.matchEmit(n?o+n+i:`.${i}`)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.#d(i,e)}walkCB(t,e,s){if(this.signal?.aborted)return s();this.walkCB2(t,e,new rs.Processor(this.opts),s)}walkCB2(t,e,s,i){if(this.#r(t)||this.signal?.aborted)return i();if(this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let n=1,o=()=>{--n===0&&i()};for(let[h,a]of s.matches.store)this.#o(h)||(n++,this.match(h,!!(a&pe),!!(a&me)).then(()=>o()));for(let h of s.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;n++;let a=h.readdirCached();h.calledReaddir()?this.walkCB3(h,a,s,o):h.readdirCB((l,c)=>this.walkCB3(h,c,s,o),!0)}o()}walkCB3(t,e,s,i){let n=s.filterEntries(t,e),o=1,h=()=>{--o===0&&i()};for(let[a,l]of n.matches.store)this.#o(a)||(o++,this.match(a,!!(l&pe),!!(l&me)).then(()=>h()));for(let[a,l]of n.subwalks.entries())o++,this.walkCB2(a,l,n.child(),h);h()}walkCBSync(t,e,s){if(this.signal?.aborted)return s();this.walkCB2Sync(t,e,new rs.Processor(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#r(t)||this.signal?.aborted)return i();if(this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let n=1,o=()=>{--n===0&&i()};for(let[h,a]of s.matches.store)this.#o(h)||this.matchSync(h,!!(a&pe),!!(a&me));for(let h of s.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;n++;let a=h.readdirSync();this.walkCB3Sync(h,a,s,o)}o()}walkCB3Sync(t,e,s,i){let n=s.filterEntries(t,e),o=1,h=()=>{--o===0&&i()};for(let[a,l]of n.matches.store)this.#o(a)||this.matchSync(a,!!(l&pe),!!(l&me));for(let[a,l]of n.subwalks.entries())o++,this.walkCB2Sync(a,l,n.child(),h);h()}};Q.GlobUtil=Pt;var os=class extends Pt{matches=[];constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.push(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}};Q.GlobWalker=os;var hs=class extends Pt{results;constructor(t,e,s){super(t,e,s),this.results=new fr.Minipass({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};Q.GlobStream=hs});var ls=C(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.Glob=void 0;var pr=Y(),mr=require("node:url"),ge=mi(),gr=ts(),we=yi(),wr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",as=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,mr.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");let s=typeof t=="string"?[t]:t;if(this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(s=s.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");s=s.map(l=>l.includes("/")?l:`./**/${l}`)}if(this.pattern=s,this.platform=e.platform||wr,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let l=e.platform==="win32"?ge.PathScurryWin32:e.platform==="darwin"?ge.PathScurryDarwin:e.platform?ge.PathScurryPosix:ge.PathScurry;this.scurry=new l(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",n={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape},o=this.pattern.map(l=>new pr.Minimatch(l,n)),[h,a]=o.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=h.map((l,c)=>{let u=a[c];if(!u)throw new Error("invalid pattern object");return new gr.Pattern(l,u,0,this.platform)})}async walk(){return await new we.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()}walkSync(){return new we.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()}stream(){return new we.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new we.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};be.Glob=as});var cs=C(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.hasMagic=void 0;var br=Y(),yr=(r,t={})=>{for(let e of Array.isArray(r)?r:[r])if(new br.Minimatch(e,t).hasMagic())return!0;return!1};ye.hasMagic=yr});Object.defineProperty(exports,"__esModule",{value:!0});exports.glob=exports.sync=exports.iterate=exports.iterateSync=exports.stream=exports.streamSync=exports.Ignore=exports.hasMagic=exports.Glob=exports.unescape=exports.escape=void 0;exports.globStreamSync=Tt;exports.globStream=us;exports.globSync=fs;exports.globIterateSync=Ft;exports.globIterate=ds;var Si=Y(),nt=ls(),Sr=cs(),_i=Y();Object.defineProperty(exports,"escape",{enumerable:!0,get:function(){return _i.escape}});Object.defineProperty(exports,"unescape",{enumerable:!0,get:function(){return _i.unescape}});var vr=ls();Object.defineProperty(exports,"Glob",{enumerable:!0,get:function(){return vr.Glob}});var _r=cs();Object.defineProperty(exports,"hasMagic",{enumerable:!0,get:function(){return _r.hasMagic}});var Er=is();Object.defineProperty(exports,"Ignore",{enumerable:!0,get:function(){return Er.Ignore}});function Tt(r,t={}){return new nt.Glob(r,t).streamSync()}function us(r,t={}){return new nt.Glob(r,t).stream()}function fs(r,t={}){return new nt.Glob(r,t).walkSync()}async function vi(r,t={}){return new nt.Glob(r,t).walk()}function Ft(r,t={}){return new nt.Glob(r,t).iterateSync()}function ds(r,t={}){return new nt.Glob(r,t).iterate()}exports.streamSync=Tt;exports.stream=Object.assign(us,{sync:Tt});exports.iterateSync=Ft;exports.iterate=Object.assign(ds,{sync:Ft});exports.sync=Object.assign(fs,{stream:Tt,iterate:Ft});exports.glob=Object.assign(vi,{glob:vi,globSync:fs,sync:exports.sync,globStream:us,stream:exports.stream,globStreamSync:Tt,streamSync:exports.streamSync,globIterate:ds,iterate:exports.iterate,globIterateSync:Ft,iterateSync:exports.iterateSync,Glob:nt.Glob,hasMagic:Sr.hasMagic,escape:Si.escape,unescape:Si.unescape});exports.glob.glob=exports.glob; //# sourceMappingURL=index.min.js.map diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.min.js.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.min.js.map index d4d78f5917a64949dbe54957e8d2b5da4d082ce4..94db77f8b6e051a621623509b76d6035cdb9d338 100644 --- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.min.js.map +++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/index.min.js.map @@ -1,7 +1,7 @@ { "version": 3, - "sources": ["../../node_modules/balanced-match/src/index.ts", "../../node_modules/brace-expansion/src/index.ts", "../../node_modules/minimatch/src/assert-valid-pattern.ts", "../../node_modules/minimatch/src/brace-expressions.ts", "../../node_modules/minimatch/src/unescape.ts", "../../node_modules/minimatch/src/ast.ts", "../../node_modules/minimatch/src/escape.ts", "../../node_modules/minimatch/src/index.ts", "../../node_modules/lru-cache/src/index.ts", "../../node_modules/minipass/src/index.ts", "../../node_modules/path-scurry/src/index.ts", "../../src/pattern.ts", "../../src/ignore.ts", "../../src/processor.ts", "../../src/walker.ts", "../../src/glob.ts", "../../src/has-magic.ts", "../../src/index.ts"], - "sourcesContent": ["export const balanced = (\n a: string | RegExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n", "import { balanced } from 'balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\./g\n\nexport const EXPANSION_MAX = 100_000\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n if (!str) {\n return ['']\n }\n\n const parts: string[] = []\n const m = balanced('{', '}', str)\n\n if (!m) {\n return str.split(',')\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n\n p[p.length - 1] += '{' + body + '}'\n const postParts = parseCommaParts(post)\n if (post.length) {\n ;(p[p.length - 1] as string) += postParts.shift()\n p.push.apply(p, postParts)\n }\n\n parts.push.apply(parts, p)\n\n return parts\n}\n\nexport type BraceExpansionOptions = {\n max?: number\n}\n\nexport function expand(str: string, options: BraceExpansionOptions = {}) {\n if (!str) {\n return []\n }\n\n const { max = EXPANSION_MAX } = options\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(escapeBraces(str), max, true).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\nfunction expand_(str: string, max: number, isTop: boolean): string[] {\n /** @type {string[]} */\n const expansions: string[] = []\n\n const m = balanced('{', '}', str)\n if (!m) return [str]\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n const post: string[] = m.post.length ? expand_(m.post, max, false) : ['']\n\n if (/\\$$/.test(m.pre)) {\n for (let k = 0; k < post.length && k < max; k++) {\n const expansion = pre + '{' + m.body + '}' + post[k]\n expansions.push(expansion)\n }\n } else {\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(\n m.body,\n )\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post\n return expand_(str, max, true)\n }\n return [str]\n }\n\n let n: string[]\n if (isSequence) {\n n = m.body.split(/\\.\\./)\n } else {\n n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(n[0], max, false).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n return post.map(p => m.pre + n[0] + p)\n }\n /* c8 ignore stop */\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n let N: string[]\n\n if (isSequence && n[0] !== undefined && n[1] !== undefined) {\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n N = []\n\n for (let i = x; test(i, y); i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n N.push(c)\n }\n } else {\n N = []\n\n for (let j = 0; j < n.length; j++) {\n N.push.apply(N, expand_(n[j] as string, max, false))\n }\n }\n\n for (let j = 0; j < N.length; j++) {\n for (let k = 0; k < post.length && expansions.length < max; k++) {\n const expansion = pre + N[j] + post[k]\n if (!isTop || isSequence || expansion) {\n expansions.push(expansion)\n }\n }\n }\n }\n\n return expansions\n}\n", "const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n pattern: any,\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n", "// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } =\n {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n '[:cntrl:]': ['\\\\p{Cc}', true],\n '[:digit:]': ['\\\\p{Nd}', true],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n '[:lower:]': ['\\\\p{Ll}', true],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}', true],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n '[:upper:]': ['\\\\p{Lu}', true],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n '[:xdigit:]': ['A-Fa-f0-9', false],\n }\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n src: string,\n uFlag: boolean,\n consumed: number,\n hasMagic: boolean,\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n glob: string,\n position: number,\n): ParseClassResult => {\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let uflag = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return ['$.', false, glob.length - pos, true]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n uflag = uflag || u\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c))\n }\n rangeStart = ''\n i++\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + 1)) {\n ranges.push(braceEscape(c + '-'))\n i += 2\n continue\n }\n if (glob.startsWith('-', i + 1)) {\n rangeStart = c\n i += 2\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(c))\n i++\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return ['', false, 0, false]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return ['$.', false, glob.length - pos, true]\n }\n\n // if we got one positive range, and it's a single character, then that's\n // not actually a magic pattern, it's just that one literal character.\n // we should not treat that as \"magic\", we should just return the literal\n // character. [_] is a perfectly valid way to escape glob magic chars.\n if (\n negs.length === 0 &&\n ranges.length === 1 &&\n /^\\\\?.$/.test(ranges[0]) &&\n !negate\n ) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n return [regexpEscape(r), false, endPos - pos, false]\n }\n\n const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n const comb =\n ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs\n\n return [comb, uflag, endPos - pos, true]\n}\n", "import { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = true,\n }: Pick = {},\n) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ?\n s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2')\n .replace(/\\\\([^\\/])/g, '$1')\n }\n return windowsPathsNoEscape ?\n s.replace(/\\[([^\\/\\\\{}])\\]/g, '$1')\n : s\n .replace(/((?!\\\\).|^)\\[([^\\/\\\\{}])\\]/g, '$1$2')\n .replace(/\\\\([^\\/{}])/g, '$1')\n}\n", "// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n// 1 2 3 4 5 6 1 2 3 46 5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n// v----- .* because there's more following,\n// v v otherwise, .+ because it must be\n// v v *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n// copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n type: ExtglobType | null\n readonly #root: AST\n\n #hasMagic?: boolean\n #uflag: boolean = false\n #parts: (string | AST)[] = []\n readonly #parent?: AST\n readonly #parentIndex: number\n #negs: AST[]\n #filledNegs: boolean = false\n #options: MinimatchOptions\n #toString?: string\n // set to true if it's an extglob with no children\n // (which really means one child of '')\n #emptyExt: boolean = false\n\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {},\n ) {\n this.type = type\n // extglobs are inherently magical\n if (type) this.#hasMagic = true\n this.#parent = parent\n this.#root = this.#parent ? this.#parent.#root : this\n this.#options = this.#root === this ? options : this.#root.#options\n this.#negs = this.#root === this ? [] : this.#root.#negs\n if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n }\n\n get hasMagic(): boolean | undefined {\n /* c8 ignore start */\n if (this.#hasMagic !== undefined) return this.#hasMagic\n /* c8 ignore stop */\n for (const p of this.#parts) {\n if (typeof p === 'string') continue\n if (p.type || p.hasMagic) return (this.#hasMagic = true)\n }\n // note: will be undefined until we generate the regexp src and find out\n return this.#hasMagic\n }\n\n // reconstructs the pattern\n toString(): string {\n if (this.#toString !== undefined) return this.#toString\n if (!this.type) {\n return (this.#toString = this.#parts.map(p => String(p)).join(''))\n } else {\n return (this.#toString =\n this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n }\n }\n\n #fillNegs() {\n /* c8 ignore start */\n if (this !== this.#root) throw new Error('should only call on root')\n if (this.#filledNegs) return this\n /* c8 ignore stop */\n\n // call toString() once to fill this out\n this.toString()\n this.#filledNegs = true\n let n: AST | undefined\n while ((n = this.#negs.pop())) {\n if (n.type !== '!') continue\n // walk up the tree, appending everthing that comes AFTER parentIndex\n let p: AST | undefined = n\n let pp = p.#parent\n while (pp) {\n for (\n let i = p.#parentIndex + 1;\n !pp.type && i < pp.#parts.length;\n i++\n ) {\n for (const part of n.#parts) {\n /* c8 ignore start */\n if (typeof part === 'string') {\n throw new Error('string part in extglob AST??')\n }\n /* c8 ignore stop */\n part.copyIn(pp.#parts[i])\n }\n }\n p = pp\n pp = p.#parent\n }\n }\n return this\n }\n\n push(...parts: (string | AST)[]) {\n for (const p of parts) {\n if (p === '') continue\n /* c8 ignore start */\n if (\n typeof p !== 'string' &&\n !(p instanceof AST && p.#parent === this)\n ) {\n throw new Error('invalid part: ' + p)\n }\n /* c8 ignore stop */\n this.#parts.push(p)\n }\n }\n\n toJSON() {\n const ret: any[] =\n this.type === null ?\n this.#parts\n .slice()\n .map(p => (typeof p === 'string' ? p : p.toJSON()))\n : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n if (this.isStart() && !this.type) ret.unshift([])\n if (\n this.isEnd() &&\n (this === this.#root ||\n (this.#root.#filledNegs && this.#parent?.type === '!'))\n ) {\n ret.push({})\n }\n return ret\n }\n\n isStart(): boolean {\n if (this.#root === this) return true\n // if (this.type) return !!this.#parent?.isStart()\n if (!this.#parent?.isStart()) return false\n if (this.#parentIndex === 0) return true\n // if everything AHEAD of this is a negation, then it's still the \"start\"\n const p = this.#parent\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i]\n if (!(pp instanceof AST && pp.type === '!')) {\n return false\n }\n }\n return true\n }\n\n isEnd(): boolean {\n if (this.#root === this) return true\n if (this.#parent?.type === '!') return true\n if (!this.#parent?.isEnd()) return false\n if (!this.type) return this.#parent?.isEnd()\n // if not root, it'll always have a parent\n /* c8 ignore start */\n const pl = this.#parent ? this.#parent.#parts.length : 0\n /* c8 ignore stop */\n return this.#parentIndex === pl - 1\n }\n\n copyIn(part: AST | string) {\n if (typeof part === 'string') this.push(part)\n else this.push(part.clone(this))\n }\n\n clone(parent: AST) {\n const c = new AST(this.type, parent)\n for (const p of this.#parts) {\n c.copyIn(p)\n }\n return c\n }\n\n static #parseAST(\n str: string,\n ast: AST,\n pos: number,\n opt: MinimatchOptions,\n ): number {\n let escaping = false\n let inBrace = false\n let braceStart = -1\n let braceNeg = false\n if (ast.type === null) {\n // outside of a extglob, append until we find a start\n let i = pos\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n ast.push(acc)\n acc = ''\n const ext = new AST(c, ast)\n i = AST.#parseAST(str, ext, i, opt)\n ast.push(ext)\n continue\n }\n acc += c\n }\n ast.push(acc)\n return i\n }\n\n // some kind of extglob, pos is at the (\n // find the next | or )\n let i = pos + 1\n let part = new AST(null, ast)\n const parts: AST[] = []\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (isExtglobType(c) && str.charAt(i) === '(') {\n part.push(acc)\n acc = ''\n const ext = new AST(c, part)\n part.push(ext)\n i = AST.#parseAST(str, ext, i, opt)\n continue\n }\n if (c === '|') {\n part.push(acc)\n acc = ''\n parts.push(part)\n part = new AST(null, ast)\n continue\n }\n if (c === ')') {\n if (acc === '' && ast.#parts.length === 0) {\n ast.#emptyExt = true\n }\n part.push(acc)\n acc = ''\n ast.push(...parts, part)\n return i\n }\n acc += c\n }\n\n // unfinished extglob\n // if we got here, it was a malformed extglob! not an extglob, but\n // maybe something else in there.\n ast.type = null\n ast.#hasMagic = undefined\n ast.#parts = [str.substring(pos - 1)]\n return i\n }\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n const ast = new AST(null, undefined, options)\n AST.#parseAST(pattern, ast, 0, options)\n return ast\n }\n\n // returns the regular expression if there's magic, or the unescaped\n // string if not.\n toMMPattern(): MMRegExp | string {\n // should only be called on root\n /* c8 ignore start */\n if (this !== this.#root) return this.#root.toMMPattern()\n /* c8 ignore stop */\n const glob = this.toString()\n const [re, body, hasMagic, uflag] = this.toRegExpSource()\n // if we're in nocase mode, and not nocaseMagicOnly, then we do\n // still need a regular expression if we have to case-insensitively\n // match capital/lowercase characters.\n const anyMagic =\n hasMagic ||\n this.#hasMagic ||\n (this.#options.nocase &&\n !this.#options.nocaseMagicOnly &&\n glob.toUpperCase() !== glob.toLowerCase())\n if (!anyMagic) {\n return body\n }\n\n const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob,\n })\n }\n\n get options() {\n return this.#options\n }\n\n // returns the string match, the regexp source, whether there's magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it's easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it's going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it's better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it's not the first pattern,\n // and the start always gets applied.\n //\n // But that's always going to be $ if it's the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it's #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(\n allowDot?: boolean,\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n const dot = allowDot ?? !!this.#options.dot\n if (this.#root === this) this.#fillNegs()\n if (!this.type) {\n const noEmpty =\n this.isStart() &&\n this.isEnd() &&\n !this.#parts.some(s => typeof s !== 'string')\n const src = this.#parts\n .map(p => {\n const [re, _, hasMagic, uflag] =\n typeof p === 'string' ?\n AST.#parseGlob(p, this.#hasMagic, noEmpty)\n : p.toRegExpSource(allowDot)\n this.#hasMagic = this.#hasMagic || hasMagic\n this.#uflag = this.#uflag || uflag\n return re\n })\n .join('')\n\n let start = ''\n if (this.isStart()) {\n if (typeof this.#parts[0] === 'string') {\n // this is the string that will match the start of the pattern,\n // so we need to protect against dots and such.\n\n // '.' and '..' cannot match unless the pattern is that exactly,\n // even if it starts with . or dot:true is set.\n const dotTravAllowed =\n this.#parts.length === 1 && justDots.has(this.#parts[0])\n if (!dotTravAllowed) {\n const aps = addPatternStart\n // check if we have a possibility of matching . or ..,\n // and prevent that.\n const needNoTrav =\n // dots are allowed, and the pattern starts with [ or .\n (dot && aps.has(src.charAt(0))) ||\n // the pattern starts with \\., and then [ or .\n (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n // the pattern starts with \\.\\., and then [ or .\n (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n // no need to prevent dots if it can't match a dot, or if a\n // sub-pattern will be preventing it anyway.\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n start =\n needNoTrav ? startNoTraversal\n : needNoDot ? startNoDot\n : ''\n }\n }\n }\n\n // append the \"end of path portion\" pattern to negation tails\n let end = ''\n if (\n this.isEnd() &&\n this.#root.#filledNegs &&\n this.#parent?.type === '!'\n ) {\n end = '(?:$|\\\\/)'\n }\n const final = start + src + end\n return [\n final,\n unescape(src),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n // We need to calculate the body *twice* if it's a repeat pattern\n // at the start, once in nodot mode, then again in dot mode, so a\n // pattern like *(?) can match 'x.y'\n\n const repeated = this.type === '*' || this.type === '+'\n // some kind of extglob\n const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n let body = this.#partsToRegExp(dot)\n\n if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n // invalid extglob, has to at least be *something* present, if it's\n // the entire path portion.\n const s = this.toString()\n this.#parts = [s]\n this.type = null\n this.#hasMagic = undefined\n return [s, unescape(this.toString()), false, false]\n }\n\n // XXX abstract out this map method\n let bodyDotAllowed =\n !repeated || allowDot || dot || !startNoDot ?\n ''\n : this.#partsToRegExp(true)\n if (bodyDotAllowed === body) {\n bodyDotAllowed = ''\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`\n }\n\n // an empty !() is exactly equivalent to a starNoEmpty\n let final = ''\n if (this.type === '!' && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n } else {\n const close =\n this.type === '!' ?\n // !() must match something,but !(x) can match ''\n '))' +\n (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n star +\n ')'\n : this.type === '@' ? ')'\n : this.type === '?' ? ')?'\n : this.type === '+' && bodyDotAllowed ? ')'\n : this.type === '*' && bodyDotAllowed ? `)?`\n : `)${this.type}`\n final = start + body + close\n }\n return [\n final,\n unescape(body),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n #partsToRegExp(dot: boolean) {\n return this.#parts\n .map(p => {\n // extglob ASTs should only contain parent ASTs\n /* c8 ignore start */\n if (typeof p === 'string') {\n throw new Error('string type in extglob ast??')\n }\n /* c8 ignore stop */\n // can ignore hasMagic, because extglobs are already always magic\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n this.#uflag = this.#uflag || uflag\n return re\n })\n .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n .join('|')\n }\n\n static #parseGlob(\n glob: string,\n hasMagic: boolean | undefined,\n noEmpty: boolean = false,\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n let escaping = false\n let re = ''\n let uflag = false\n // multiple stars that aren't globstars coalesce into one *\n let inStar = false\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i)\n if (escaping) {\n escaping = false\n re += (reSpecials.has(c) ? '\\\\' : '') + c\n continue\n }\n if (c === '*') {\n if (inStar) continue\n inStar = true\n re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star\n hasMagic = true\n continue\n } else {\n inStar = false\n }\n if (c === '\\\\') {\n if (i === glob.length - 1) {\n re += '\\\\\\\\'\n } else {\n escaping = true\n }\n continue\n }\n if (c === '[') {\n const [src, needUflag, consumed, magic] = parseClass(glob, i)\n if (consumed) {\n re += src\n uflag = uflag || needUflag\n i += consumed - 1\n hasMagic = hasMagic || magic\n continue\n }\n }\n if (c === '?') {\n re += qmark\n hasMagic = true\n continue\n }\n re += regExpEscape(c)\n }\n return [re, unescape(glob), !!hasMagic, uflag]\n }\n}\n", "import { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = false,\n }: Pick = {},\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n if (magicalBraces) {\n return windowsPathsNoEscape ?\n s.replace(/[?*()[\\]{}]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n }\n return windowsPathsNoEscape ?\n s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n", "import { expand } from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\nexport type Platform =\n | 'aix'\n | 'android'\n | 'darwin'\n | 'freebsd'\n | 'haiku'\n | 'linux'\n | 'openbsd'\n | 'sunos'\n | 'win32'\n | 'cygwin'\n | 'netbsd'\n\nexport interface MinimatchOptions {\n /** do not expand `{x,y}` style braces */\n nobrace?: boolean\n /** do not treat patterns starting with `#` as a comment */\n nocomment?: boolean\n /** do not treat patterns starting with `!` as a negation */\n nonegate?: boolean\n /** print LOTS of debugging output */\n debug?: boolean\n /** treat `**` the same as `*` */\n noglobstar?: boolean\n /** do not expand extglobs like `+(a|b)` */\n noext?: boolean\n /** return the pattern if nothing matches */\n nonull?: boolean\n /** treat `\\\\` as a path separator, not an escape character */\n windowsPathsNoEscape?: boolean\n /**\n * inverse of {@link MinimatchOptions.windowsPathsNoEscape}\n * @deprecated\n */\n allowWindowsEscape?: boolean\n /**\n * Compare a partial path to a pattern. As long as the parts\n * of the path that are present are not contradicted by the\n * pattern, it will be treated as a match. This is useful in\n * applications where you're walking through a folder structure,\n * and don't yet have the full path, but want to ensure that you\n * do not walk down paths that can never be a match.\n */\n partial?: boolean\n /** allow matches that start with `.` even if the pattern does not */\n dot?: boolean\n /** ignore case */\n nocase?: boolean\n /** ignore case only in wildcard patterns */\n nocaseMagicOnly?: boolean\n /** consider braces to be \"magic\" for the purpose of `hasMagic` */\n magicalBraces?: boolean\n /**\n * If set, then patterns without slashes will be matched\n * against the basename of the path if it contains slashes.\n * For example, `a?b` would match the path `/xyz/123/acb`, but\n * not `/xyz/acb/123`.\n */\n matchBase?: boolean\n /** invert the results of negated matches */\n flipNegate?: boolean\n /** do not collapse multiple `/` into a single `/` */\n preserveMultipleSlashes?: boolean\n /**\n * A number indicating the level of optimization that should be done\n * to the pattern prior to parsing and using it for matches.\n */\n optimizationLevel?: number\n /** operating system platform */\n platform?: Platform\n /**\n * When a pattern starts with a UNC path or drive letter, and in\n * `nocase:true` mode, do not convert the root portions of the\n * pattern into a case-insensitive regular expression, and instead\n * leave them as strings.\n *\n * This is the default when the platform is `win32` and\n * `nocase:true` is set.\n */\n windowsNoMagicRoot?: boolean\n /**\n * max number of `{...}` patterns to expand. Default 100_000.\n */\n braceExpandMax?: number\n}\n\nexport const minimatch = (\n p: string,\n pattern: string,\n options: MinimatchOptions = {},\n) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) =>\n !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) =>\n f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) =>\n f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n typeof process === 'object' && process ?\n (typeof process.env === 'object' &&\n process.env &&\n process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n process.platform\n : 'posix') as Platform\n\nexport type Sep = '\\\\' | '/'\n\nconst path: { [k: string]: { sep: Sep } } = {\n win32: { sep: '\\\\' },\n posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep =\n defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n (pattern: string, options: MinimatchOptions = {}) =>\n (p: string) =>\n minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n orig(p, pattern, ext(def, options))\n\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern: string, options: MinimatchOptions = {}) {\n super(pattern, ext(def, options))\n }\n static defaults(options: MinimatchOptions) {\n return orig.defaults(ext(def, options)).Minimatch\n }\n },\n\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {},\n ) {\n super(type, parent, ext(def, options))\n }\n /* c8 ignore stop */\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options))\n }\n },\n\n unescape: (\n s: string,\n options: Pick<\n MinimatchOptions,\n 'windowsPathsNoEscape' | 'magicalBraces'\n > = {},\n ) => orig.unescape(s, ext(def, options)),\n\n escape: (\n s: string,\n options: Pick<\n MinimatchOptions,\n 'windowsPathsNoEscape' | 'magicalBraces'\n > = {},\n ) => orig.escape(s, ext(def, options)),\n\n filter: (pattern: string, options: MinimatchOptions = {}) =>\n orig.filter(pattern, ext(def, options)),\n\n defaults: (options: MinimatchOptions) =>\n orig.defaults(ext(def, options)),\n\n makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n orig.makeRe(pattern, ext(def, options)),\n\n braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n orig.braceExpand(pattern, ext(def, options)),\n\n match: (\n list: string[],\n pattern: string,\n options: MinimatchOptions = {},\n ) => orig.match(list, pattern, ext(def, options)),\n\n sep: orig.sep,\n GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n pattern: string,\n options: MinimatchOptions = {},\n) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern, { max: options.braceExpandMax })\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n list: string[],\n pattern: string,\n options: MinimatchOptions = {},\n) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n _src?: string\n _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n options: MinimatchOptions\n set: ParseReturnFiltered[][]\n pattern: string\n\n windowsPathsNoEscape: boolean\n nonegate: boolean\n negate: boolean\n comment: boolean\n empty: boolean\n preserveMultipleSlashes: boolean\n partial: boolean\n globSet: string[]\n globParts: string[][]\n nocase: boolean\n\n isWindows: boolean\n platform: Platform\n windowsNoMagicRoot: boolean\n\n regexp: false | null | MMRegExp\n constructor(pattern: string, options: MinimatchOptions = {}) {\n assertValidPattern(pattern)\n\n options = options || {}\n this.options = options\n this.pattern = pattern\n this.platform = options.platform || defaultPlatform\n this.isWindows = this.platform === 'win32'\n // avoid the annoying deprecation flag lol\n const awe = ('allowWindow' + 'sEscape') as keyof MinimatchOptions\n this.windowsPathsNoEscape =\n !!options.windowsPathsNoEscape || options[awe] === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n this.regexp = null\n this.negate = false\n this.nonegate = !!options.nonegate\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n this.nocase = !!this.options.nocase\n this.windowsNoMagicRoot =\n options.windowsNoMagicRoot !== undefined ?\n options.windowsNoMagicRoot\n : !!(this.isWindows && this.nocase)\n\n this.globSet = []\n this.globParts = []\n this.set = []\n\n // make the set of regexps etc.\n this.make()\n }\n\n hasMagic(): boolean {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== 'string') return true\n }\n }\n return false\n }\n\n debug(..._: any[]) {}\n\n make() {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n this.globSet = [...new Set(this.braceExpand())]\n\n if (options.debug) {\n this.debug = (...args: any[]) => console.error(...args)\n }\n\n this.debug(this.pattern, this.globSet)\n\n // step 3: now we have a set, so turn each one into a series of\n // path-portion matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n //\n // First, we preprocess to make the glob pattern sets a bit simpler\n // and deduped. There are some perf-killing patterns that can cause\n // problems with a glob walk, but we can simplify them down a bit.\n const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n this.globParts = this.preprocess(rawGlobParts)\n this.debug(this.pattern, this.globParts)\n\n // glob --> regexps\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n // check if it's a drive or unc path.\n const isUNC =\n s[0] === '' &&\n s[1] === '' &&\n (s[2] === '?' || !globMagic.test(s[2])) &&\n !globMagic.test(s[3])\n const isDrive = /^[a-z]:/i.test(s[0])\n if (isUNC) {\n return [\n ...s.slice(0, 4),\n ...s.slice(4).map(ss => this.parse(ss)),\n ]\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n }\n }\n return s.map(ss => this.parse(ss))\n })\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n this.set = set.filter(\n s => s.indexOf(false) === -1,\n ) as ParseReturnFiltered[][]\n\n // do not treat the ? in UNC paths as magic\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i]\n if (\n p[0] === '' &&\n p[1] === '' &&\n this.globParts[i][2] === '?' &&\n typeof p[3] === 'string' &&\n /^[a-z]:$/i.test(p[3])\n ) {\n p[2] = '?'\n }\n }\n }\n\n this.debug(this.pattern, this.set)\n }\n\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts: string[][]) {\n // if we're not in globstar mode, then turn ** into *\n if (this.options.noglobstar) {\n for (let i = 0; i < globParts.length; i++) {\n for (let j = 0; j < globParts[i].length; j++) {\n if (globParts[i][j] === '**') {\n globParts[i][j] = '*'\n }\n }\n }\n }\n\n const { optimizationLevel = 1 } = this.options\n\n if (optimizationLevel >= 2) {\n // aggressive optimization for the purpose of fs walking\n globParts = this.firstPhasePreProcess(globParts)\n globParts = this.secondPhasePreProcess(globParts)\n } else if (optimizationLevel >= 1) {\n // just basic optimizations to remove some .. parts\n globParts = this.levelOneOptimize(globParts)\n } else {\n // just collapse multiple ** portions into one\n globParts = this.adjascentGlobstarOptimize(globParts)\n }\n\n return globParts\n }\n\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let i = gs\n while (parts[i + 1] === '**') {\n i++\n }\n if (i !== gs) {\n parts.splice(gs, i - gs)\n }\n }\n return parts\n })\n }\n\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n parts = parts.reduce((set: string[], part) => {\n const prev = set[set.length - 1]\n if (part === '**' && prev === '**') {\n return set\n }\n if (part === '..') {\n if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n set.pop()\n return set\n }\n }\n set.push(part)\n return set\n }, [])\n return parts.length === 0 ? [''] : parts\n })\n }\n\n levelTwoFileOptimize(parts: string | string[]) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts)\n }\n let didSomething: boolean = false\n do {\n didSomething = false\n //
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes,\n        )\n        if (matched) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false,\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean = false,\n  ) {\n    const options = this.options\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi =\n        fileUNC ? 3\n        : fileDrive ? 0\n        : undefined\n      const pdi =\n        patternUNC ? 3\n        : patternDrive ? 0\n        : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          if (pdi > fdi) {\n            pattern = pattern.slice(pdi)\n          } else if (fdi > pdi) {\n            file = file.slice(fdi)\n          }\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // don't need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    this.debug('matchOne', this, { file, pattern })\n    this.debug('matchOne', file.length, pattern.length)\n\n    for (\n      var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      var p = pattern[pi]\n      var f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      // should be impossible.\n      // some invalid regexp stuff in the set.\n      /* c8 ignore start */\n      if (p === false) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      if (p === GLOBSTAR) {\n        this.debug('GLOBSTAR', [pattern, p, f])\n\n        // \"**\"\n        // a/**/b/**/c would match the following:\n        // a/b/x/y/z/c\n        // a/x/y/z/b/c\n        // a/b/x/b/x/c\n        // a/b/c\n        // To do this, take the rest of the pattern after\n        // the **, and see if it would match the file remainder.\n        // If so, return success.\n        // If not, the ** \"swallows\" a segment, and try again.\n        // This is recursively awful.\n        //\n        // a/**/b/**/c matching a/b/x/y/z/c\n        // - a matches a\n        // - doublestar\n        //   - matchOne(b/x/y/z/c, b/**/c)\n        //     - b matches b\n        //     - doublestar\n        //       - matchOne(x/y/z/c, c) -> no\n        //       - matchOne(y/z/c, c) -> no\n        //       - matchOne(z/c, c) -> no\n        //       - matchOne(c, c) yes, hit\n        var fr = fi\n        var pr = pi + 1\n        if (pr === pl) {\n          this.debug('** at the end')\n          // a ** at the end will just swallow the rest.\n          // We have found a match.\n          // however, it will not swallow /.x, unless\n          // options.dot is set.\n          // . and .. are *never* matched by **, for explosively\n          // exponential reasons.\n          for (; fi < fl; fi++) {\n            if (\n              file[fi] === '.' ||\n              file[fi] === '..' ||\n              (!options.dot && file[fi].charAt(0) === '.')\n            )\n              return false\n          }\n          return true\n        }\n\n        // ok, let's see if we can swallow whatever we can.\n        while (fr < fl) {\n          var swallowee = file[fr]\n\n          this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n          // XXX remove this slice.  Just pass the start index.\n          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n            this.debug('globstar found match!', fr, fl, swallowee)\n            // found a match.\n            return true\n          } else {\n            // can't swallow \".\" or \"..\" ever.\n            // can only swallow \".foo\" when explicitly asked.\n            if (\n              swallowee === '.' ||\n              swallowee === '..' ||\n              (!options.dot && swallowee.charAt(0) === '.')\n            ) {\n              this.debug('dot detected!', file, fr, pattern, pr)\n              break\n            }\n\n            // ** swallows a segment, and continue.\n            this.debug('globstar swallow a segment, and continue')\n            fr++\n          }\n        }\n\n        // no match was found.\n        // However, in partial mode, we can't say this is necessarily over.\n        /* c8 ignore start */\n        if (partial) {\n          // ran out of file\n          this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n          if (fr === fl) {\n            return true\n          }\n        }\n        /* c8 ignore stop */\n        return false\n      }\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into regexps.\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though \"\" matches against the\n    // [^/]*? pattern, except in partial mode, where it might\n    // simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase ?\n          options.dot ?\n            starDotExtTestNocaseDot\n          : starDotExtTestNocase\n        : options.dot ? starDotExtTestDot\n        : starDotExtTest)(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase ?\n          options.dot ?\n            qmarksTestNocaseDot\n          : qmarksTestNocase\n        : options.dot ? qmarksTestDot\n        : qmarksTest)(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar =\n      options.noglobstar ? star\n      : options.dot ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return (\n            typeof p === 'string' ? regExpEscape(p)\n            : p === GLOBSTAR ? GLOBSTAR\n            : p._src\n          )\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        const filtered = pp.filter(p => p !== GLOBSTAR)\n\n        // For partial matches, we need to make the pattern match\n        // any prefix of the full path. We do this by generating\n        // alternative patterns that match progressively longer prefixes.\n        if (this.partial && filtered.length >= 1) {\n          const prefixes: string[] = []\n          for (let i = 1; i <= filtered.length; i++) {\n            prefixes.push(filtered.slice(0, i).join('/'))\n          }\n          return '(?:' + prefixes.join('|') + ')'\n        }\n\n        return filtered.join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // In partial mode, '/' should always match as it's a valid prefix for any pattern\n    if (this.partial) {\n      re = '^(?:\\\\/|' + open + re.slice(1, -1) + close + ')$'\n    }\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch (ex) {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let i = 0; i < set.length; i++) {\n      const pattern = set[i]\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n", "/**\n * @module LRUCache\n */\n\n// module-private names and types\n// this provides the default Perf object source.\n// it can be passed in via configuration to override it\n// for a single LRU object.\nexport type Perf = { now: () => number }\nconst defaultPerf: Perf =\n  (\n    typeof performance === 'object' &&\n    performance &&\n    typeof performance.now === 'function'\n  ) ?\n    performance\n  : Date\n\nconst warned = new Set()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n  typeof process === 'object' && !!process ?\n    process\n  : {}) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n  msg: string,\n  type: string,\n  code: string,\n  fn: ForC,\n) => {\n  typeof PROCESS.emitWarning === 'function' ?\n    PROCESS.emitWarning(msg, type, code, fn)\n  : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n  //@ts-ignore\n  AS = class AbortSignal {\n    onabort?: (...a: any[]) => any\n    _onabort: ((...a: any[]) => any)[] = []\n    reason?: any\n    aborted: boolean = false\n    addEventListener(_: string, fn: (...a: any[]) => any) {\n      this._onabort.push(fn)\n    }\n  }\n  //@ts-ignore\n  AC = class AbortController {\n    constructor() {\n      warnACPolyfill()\n    }\n    signal = new AS()\n    abort(reason: any) {\n      if (this.signal.aborted) return\n      //@ts-ignore\n      this.signal.reason = reason\n      //@ts-ignore\n      this.signal.aborted = true\n      //@ts-ignore\n      for (const fn of this.signal._onabort) {\n        fn(reason)\n      }\n      this.signal.onabort?.(reason)\n    }\n  }\n  let printACPolyfillWarning =\n    PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n  const warnACPolyfill = () => {\n    if (!printACPolyfillWarning) return\n    printACPolyfillWarning = false\n    emitWarning(\n      'AbortController is not defined. If using lru-cache in ' +\n        'node 14, load an AbortController polyfill from the ' +\n        '`node-abort-controller` package. A minimal polyfill is ' +\n        'provided for use by LRUCache.fetch(), but it should not be ' +\n        'relied upon in other contexts (eg, passing it to other APIs that ' +\n        'use AbortController/AbortSignal might have undesirable effects). ' +\n        'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n      'NO_ABORT_CONTROLLER',\n      'ENOTSUP',\n      warnACPolyfill,\n    )\n  }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n  n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values.  Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n  !isPosInt(max) ? null\n  : max <= Math.pow(2, 8) ? Uint8Array\n  : max <= Math.pow(2, 16) ? Uint16Array\n  : max <= Math.pow(2, 32) ? Uint32Array\n  : max <= Number.MAX_SAFE_INTEGER ? ZeroArray\n  : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array {\n  constructor(size: number) {\n    super(size)\n    this.fill(0)\n  }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n  heap: NumberArray\n  length: number\n  // private constructor\n  static #constructing: boolean = false\n  static create(max: number): StackLike {\n    const HeapCls = getUintArray(max)\n    if (!HeapCls) return []\n    Stack.#constructing = true\n    const s = new Stack(max, HeapCls)\n    Stack.#constructing = false\n    return s\n  }\n  constructor(max: number, HeapCls: { new (n: number): NumberArray }) {\n    /* c8 ignore start */\n    if (!Stack.#constructing) {\n      throw new TypeError('instantiate Stack using Stack.create(n)')\n    }\n    /* c8 ignore stop */\n    this.heap = new HeapCls(max)\n    this.length = 0\n  }\n  push(n: Index) {\n    this.heap[this.length++] = n\n  }\n  pop(): Index {\n    return this.heap[--this.length] as Index\n  }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch = Promise & {\n  __returned: BackgroundFetch | undefined\n  __abortController: AbortController\n  __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask = [\n  value: V,\n  key: K,\n  reason: LRUCache.DisposeReason,\n]\n\nexport namespace LRUCache {\n  /**\n   * An integer greater than 0, reflecting the calculated size of items\n   */\n  export type Size = number\n\n  /**\n   * Integer greater than 0, representing some number of milliseconds, or the\n   * time at which a TTL started counting from.\n   */\n  export type Milliseconds = number\n\n  /**\n   * An integer greater than 0, reflecting a number of items\n   */\n  export type Count = number\n\n  /**\n   * The reason why an item was removed from the cache, passed\n   * to the {@link Disposer} methods.\n   *\n   * - `evict`: The item was evicted because it is the least recently used,\n   *   and the cache is full.\n   * - `set`: A new value was set, overwriting the old value being disposed.\n   * - `delete`: The item was explicitly deleted, either by calling\n   *   {@link LRUCache#delete}, {@link LRUCache#clear}, or\n   *   {@link LRUCache#set} with an undefined value.\n   * - `expire`: The item was removed due to exceeding its TTL.\n   * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n   *   `undefined` or was aborted, causing the item to be deleted.\n   */\n  export type DisposeReason =\n    | 'evict'\n    | 'set'\n    | 'delete'\n    | 'expire'\n    | 'fetch'\n  /**\n   * A method called upon item removal, passed as the\n   * {@link OptionsBase.dispose} and/or\n   * {@link OptionsBase.disposeAfter} options.\n   */\n  export type Disposer = (\n    value: V,\n    key: K,\n    reason: DisposeReason,\n  ) => void\n\n  /**\n   * The reason why an item was added to the cache, passed\n   * to the {@link Inserter} methods.\n   *\n   * - `add`: the item was not found in the cache, and was added\n   * - `update`: the item was in the cache, with the same value provided\n   * - `replace`: the item was in the cache, and replaced\n   */\n  export type InsertReason = 'add' | 'update' | 'replace'\n\n  /**\n   * A method called upon item insertion, passed as the\n   * {@link OptionsBase.insert}\n   */\n  export type Inserter = (\n    value: V,\n    key: K,\n    reason: InsertReason,\n  ) => void\n\n  /**\n   * A function that returns the effective calculated size\n   * of an entry in the cache.\n   */\n  export type SizeCalculator = (value: V, key: K) => Size\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.fetchMethod} function.\n   */\n  export interface FetcherOptions {\n    signal: AbortSignal\n    options: FetcherFetchOptions\n    /**\n     * Object provided in the {@link FetchOptions.context} option to\n     * {@link LRUCache#fetch}\n     */\n    context: FC\n  }\n\n  /**\n   * Occasionally, it may be useful to track the internal behavior of the\n   * cache, particularly for logging, debugging, or for behavior within the\n   * `fetchMethod`. To do this, you can pass a `status` object to the\n   * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n   * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n   *\n   * The `status` option should be a plain JavaScript object. The following\n   * fields will be set on it appropriately, depending on the situation.\n   */\n  export interface Status {\n    /**\n     * The status of a set() operation.\n     *\n     * - add: the item was not found in the cache, and was added\n     * - update: the item was in the cache, with the same value provided\n     * - replace: the item was in the cache, and replaced\n     * - miss: the item was not added to the cache for some reason\n     */\n    set?: 'add' | 'update' | 'replace' | 'miss'\n\n    /**\n     * the ttl stored for the item, or undefined if ttls are not used.\n     */\n    ttl?: Milliseconds\n\n    /**\n     * the start time for the item, or undefined if ttls are not used.\n     */\n    start?: Milliseconds\n\n    /**\n     * The timestamp used for TTL calculation\n     */\n    now?: Milliseconds\n\n    /**\n     * the remaining ttl for the item, or undefined if ttls are not used.\n     */\n    remainingTTL?: Milliseconds\n\n    /**\n     * The calculated size for the item, if sizes are used.\n     */\n    entrySize?: Size\n\n    /**\n     * The total calculated size of the cache, if sizes are used.\n     */\n    totalCalculatedSize?: Size\n\n    /**\n     * A flag indicating that the item was not stored, due to exceeding the\n     * {@link OptionsBase.maxEntrySize}\n     */\n    maxEntrySizeExceeded?: true\n\n    /**\n     * The old value, specified in the case of `set:'update'` or\n     * `set:'replace'`\n     */\n    oldValue?: V\n\n    /**\n     * The results of a {@link LRUCache#has} operation\n     *\n     * - hit: the item was found in the cache\n     * - stale: the item was found in the cache, but is stale\n     * - miss: the item was not found in the cache\n     */\n    has?: 'hit' | 'stale' | 'miss'\n\n    /**\n     * The status of a {@link LRUCache#fetch} operation.\n     * Note that this can change as the underlying fetch() moves through\n     * various states.\n     *\n     * - inflight: there is another fetch() for this key which is in process\n     * - get: there is no {@link OptionsBase.fetchMethod}, so\n     *   {@link LRUCache#get} was called.\n     * - miss: the item is not in cache, and will be fetched.\n     * - hit: the item is in the cache, and was resolved immediately.\n     * - stale: the item is in the cache, but stale.\n     * - refresh: the item is in the cache, and not stale, but\n     *   {@link FetchOptions.forceRefresh} was specified.\n     */\n    fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n    /**\n     * The {@link OptionsBase.fetchMethod} was called\n     */\n    fetchDispatched?: true\n\n    /**\n     * The cached value was updated after a successful call to\n     * {@link OptionsBase.fetchMethod}\n     */\n    fetchUpdated?: true\n\n    /**\n     * The reason for a fetch() rejection.  Either the error raised by the\n     * {@link OptionsBase.fetchMethod}, or the reason for an\n     * AbortSignal.\n     */\n    fetchError?: Error\n\n    /**\n     * The fetch received an abort signal\n     */\n    fetchAborted?: true\n\n    /**\n     * The abort signal received was ignored, and the fetch was allowed to\n     * continue.\n     */\n    fetchAbortIgnored?: true\n\n    /**\n     * The fetchMethod promise resolved successfully\n     */\n    fetchResolved?: true\n\n    /**\n     * The fetchMethod promise was rejected\n     */\n    fetchRejected?: true\n\n    /**\n     * The status of a {@link LRUCache#get} operation.\n     *\n     * - fetching: The item is currently being fetched.  If a previous value\n     *   is present and allowed, that will be returned.\n     * - stale: The item is in the cache, and is stale.\n     * - hit: the item is in the cache\n     * - miss: the item is not in the cache\n     */\n    get?: 'stale' | 'hit' | 'miss'\n\n    /**\n     * A fetch or get operation returned a stale value.\n     */\n    returnedStale?: true\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#fetch}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link OptionsBase.noDeleteOnFetchRejection},\n   * {@link OptionsBase.allowStaleOnFetchRejection},\n   * {@link FetchOptions.forceRefresh}, and\n   * {@link FetcherOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the fetchMethod is called.\n   */\n  export interface FetcherFetchOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n      | 'noDeleteOnFetchRejection'\n      | 'allowStaleOnFetchRejection'\n      | 'ignoreFetchAbort'\n      | 'allowStaleOnFetchAbort'\n    > {\n    status?: Status\n    size?: Size\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#fetch} method.\n   */\n  export interface FetchOptions\n    extends FetcherFetchOptions {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.fetchMethod} as\n     * the {@link FetcherOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    signal?: AbortSignal\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface FetchOptionsWithContext\n    extends FetchOptions {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface FetchOptionsNoContext\n    extends FetchOptions {\n    context?: undefined\n  }\n\n  export interface MemoOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n      | 'noDeleteOnFetchRejection'\n      | 'allowStaleOnFetchRejection'\n      | 'ignoreFetchAbort'\n      | 'allowStaleOnFetchAbort'\n    > {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.memoMethod} as\n     * the {@link MemoizerOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface MemoOptionsWithContext\n    extends MemoOptions {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface MemoOptionsNoContext\n    extends MemoOptions {\n    context?: undefined\n  }\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.memoMethod} function.\n   */\n  export interface MemoizerOptions {\n    options: MemoizerMemoOptions\n    /**\n     * Object provided in the {@link MemoOptions.context} option to\n     * {@link LRUCache#memo}\n     */\n    context: FC\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#memo}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link MemoOptions.forceRefresh}, and\n   * {@link MemoOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.memoMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the memoMethod is called.\n   */\n  export interface MemoizerMemoOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n    > {\n    status?: Status\n    size?: Size\n    start?: Milliseconds\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#has} method.\n   */\n  export interface HasOptions\n    extends Pick, 'updateAgeOnHas'> {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#get} method.\n   */\n  export interface GetOptions\n    extends Pick<\n      OptionsBase,\n      'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n    > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#peek} method.\n   */\n  export interface PeekOptions\n    extends Pick, 'allowStale'> {}\n\n  /**\n   * Options that may be passed to the {@link LRUCache#set} method.\n   */\n  export interface SetOptions\n    extends Pick<\n      OptionsBase,\n      'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n    > {\n    /**\n     * If size tracking is enabled, then setting an explicit size\n     * in the {@link LRUCache#set} call will prevent calling the\n     * {@link OptionsBase.sizeCalculation} function.\n     */\n    size?: Size\n    /**\n     * If TTL tracking is enabled, then setting an explicit start\n     * time in the {@link LRUCache#set} call will override the\n     * default time from `performance.now()` or `Date.now()`.\n     *\n     * Note that it must be a valid value for whichever time-tracking\n     * method is in use.\n     */\n    start?: Milliseconds\n    status?: Status\n  }\n\n  /**\n   * The type signature for the {@link OptionsBase.fetchMethod} option.\n   */\n  export type Fetcher = (\n    key: K,\n    staleValue: V | undefined,\n    options: FetcherOptions,\n  ) => Promise | V | undefined | void\n\n  /**\n   * the type signature for the {@link OptionsBase.memoMethod} option.\n   */\n  export type Memoizer = (\n    key: K,\n    staleValue: V | undefined,\n    options: MemoizerOptions,\n  ) => V\n\n  /**\n   * Options which may be passed to the {@link LRUCache} constructor.\n   *\n   * Most of these may be overridden in the various options that use\n   * them.\n   *\n   * Despite all being technically optional, the constructor requires that\n   * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n   * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n   *\n   * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n   * (and in fact required by the type definitions here) that the cache\n   * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n   * unbounded storage.\n   *\n   * All options are also available on the {@link LRUCache} instance, making\n   * it safe to pass an LRUCache instance as the options argumemnt to\n   * make another empty cache of the same type.\n   *\n   * Some options are marked as read-only, because changing them after\n   * instantiation is not safe. Changing any of the other options will of\n   * course only have an effect on subsequent method calls.\n   */\n  export interface OptionsBase {\n    /**\n     * The maximum number of items to store in the cache before evicting\n     * old entries. This is read-only on the {@link LRUCache} instance,\n     * and may not be overridden.\n     *\n     * If set, then storage space will be pre-allocated at construction\n     * time, and the cache will perform significantly faster.\n     *\n     * Note that significantly fewer items may be stored, if\n     * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n     * set.\n     *\n     * **It is strongly recommended to set a `max` to prevent unbounded growth\n     * of the cache.**\n     */\n    max?: Count\n\n    /**\n     * Max time in milliseconds for items to live in cache before they are\n     * considered stale.  Note that stale items are NOT preemptively removed by\n     * default, and MAY live in the cache, contributing to its LRU max, long\n     * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n     * set.\n     *\n     * If set to `0` (the default value), then that means \"do not track\n     * TTL\", not \"expire immediately\".\n     *\n     * Also, as this cache is optimized for LRU/MRU operations, some of\n     * the staleness/TTL checks will reduce performance, as they will incur\n     * overhead by deleting items.\n     *\n     * This is not primarily a TTL cache, and does not make strong TTL\n     * guarantees. There is no pre-emptive pruning of expired items, but you\n     * _may_ set a TTL on the cache, and it will treat expired items as missing\n     * when they are fetched, and delete them.\n     *\n     * Optional, but must be a non-negative integer in ms if specified.\n     *\n     * This may be overridden by passing an options object to `cache.set()`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if ttl tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n     * and `ttlAutopurge` is not set, then a warning will be emitted\n     * cautioning about the potential for unbounded memory consumption.\n     * (The TypeScript definitions will also discourage this.)\n     */\n    ttl?: Milliseconds\n\n    /**\n     * Minimum amount of time in ms in which to check for staleness.\n     * Defaults to 1, which means that the current time is checked\n     * at most once per millisecond.\n     *\n     * Set to 0 to check the current time every time staleness is tested.\n     * (This reduces performance, and is theoretically unnecessary.)\n     *\n     * Setting this to a higher value will improve performance somewhat\n     * while using ttl tracking, albeit at the expense of keeping stale\n     * items around a bit longer than their TTLs would indicate.\n     *\n     * @default 1\n     */\n    ttlResolution?: Milliseconds\n\n    /**\n     * Preemptively remove stale items from the cache.\n     *\n     * Note that this may *significantly* degrade performance, especially if\n     * the cache is storing a large number of items. It is almost always best\n     * to just leave the stale items in the cache, and let them fall out as new\n     * items are added.\n     *\n     * Note that this means that {@link OptionsBase.allowStale} is a bit\n     * pointless, as stale items will be deleted almost as soon as they\n     * expire.\n     *\n     * Use with caution!\n     */\n    ttlAutopurge?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever it is retrieved from cache with\n     * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n     * of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     */\n    updateAgeOnGet?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever its presence in the cache is\n     * checked with {@link LRUCache#has}, causing it to not expire. (It can\n     * still fall out of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     */\n    updateAgeOnHas?: boolean\n\n    /**\n     * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n     * stale data, if available.\n     *\n     * By default, if you set `ttl`, stale items will only be deleted from the\n     * cache when you `get(key)`. That is, it's not preemptively pruning items,\n     * unless {@link OptionsBase.ttlAutopurge} is set.\n     *\n     * If you set `allowStale:true`, it'll return the stale value *as well as*\n     * deleting it. If you don't set this, then it'll return `undefined` when\n     * you try to get a stale entry.\n     *\n     * Note that when a stale entry is fetched, _even if it is returned due to\n     * `allowStale` being set_, it is removed from the cache immediately. You\n     * can suppress this behavior by setting\n     * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n     * the options provided to {@link LRUCache#get}.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     * The `cache.has()` method will always return `false` for stale items.\n     *\n     * Only relevant if a ttl is set.\n     */\n    allowStale?: boolean\n\n    /**\n     * Function that is called on items when they are dropped from the\n     * cache, as `dispose(value, key, reason)`.\n     *\n     * This can be handy if you want to close file descriptors or do\n     * other cleanup tasks when items are no longer stored in the cache.\n     *\n     * **NOTE**: It is called _before_ the item has been fully removed\n     * from the cache, so if you want to put it right back in, you need\n     * to wait until the next tick. If you try to add it back in during\n     * the `dispose()` function call, it will break things in subtle and\n     * weird ways.\n     *\n     * Unlike several other options, this may _not_ be overridden by\n     * passing an option to `set()`, for performance reasons.\n     *\n     * The `reason` will be one of the following strings, corresponding\n     * to the reason for the item's deletion:\n     *\n     * - `evict` Item was evicted to make space for a new addition\n     * - `set` Item was overwritten by a new value\n     * - `expire` Item expired its TTL\n     * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n     *   fetchMethod returning `undefined.\n     * - `delete` Item was removed by explicit `cache.delete(key)`,\n     *   `cache.clear()`, or `cache.set(key, undefined)`.\n     */\n    dispose?: Disposer\n\n    /**\n     * Function that is called when new items are inserted into the cache,\n     * as `onInsert(value, key, reason)`.\n     *\n     * This can be useful if you need to perform actions when an item is\n     * added, such as logging or tracking insertions.\n     *\n     * Unlike some other options, this may _not_ be overridden by passing\n     * an option to `set()`, for performance and consistency reasons.\n     */\n    onInsert?: Inserter\n\n    /**\n     * The same as {@link OptionsBase.dispose}, but called *after* the entry\n     * is completely removed and the cache is once again in a clean state.\n     *\n     * It is safe to add an item right back into the cache at this point.\n     * However, note that it is *very* easy to inadvertently create infinite\n     * recursion this way.\n     */\n    disposeAfter?: Disposer\n\n    /**\n     * Set to true to suppress calling the\n     * {@link OptionsBase.dispose} function if the entry key is\n     * still accessible within the cache.\n     *\n     * This may be overridden by passing an options object to\n     * {@link LRUCache#set}.\n     *\n     * Only relevant if `dispose` or `disposeAfter` are set.\n     */\n    noDisposeOnSet?: boolean\n\n    /**\n     * Boolean flag to tell the cache to not update the TTL when setting a new\n     * value for an existing key (ie, when updating a value rather than\n     * inserting a new value).  Note that the TTL value is _always_ set (if\n     * provided) when adding a new entry into the cache.\n     *\n     * Has no effect if a {@link OptionsBase.ttl} is not set.\n     *\n     * May be passed as an option to {@link LRUCache#set}.\n     */\n    noUpdateTTL?: boolean\n\n    /**\n     * Set to a positive integer to track the sizes of items added to the\n     * cache, and automatically evict items in order to stay below this size.\n     * Note that this may result in fewer than `max` items being stored.\n     *\n     * Attempting to add an item to the cache whose calculated size is greater\n     * that this amount will be a no-op. The item will not be cached, and no\n     * other items will be evicted.\n     *\n     * Optional, must be a positive integer if provided.\n     *\n     * Sets `maxEntrySize` to the same value, unless a different value is\n     * provided for `maxEntrySize`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if size tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * Note also that size tracking can negatively impact performance,\n     * though for most cases, only minimally.\n     */\n    maxSize?: Size\n\n    /**\n     * The maximum allowed size for any single item in the cache.\n     *\n     * If a larger item is passed to {@link LRUCache#set} or returned by a\n     * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n     * it will not be stored in the cache.\n     *\n     * Attempting to add an item whose calculated size is greater than\n     * this amount will not cache the item or evict any old items, but\n     * WILL delete an existing value if one is already present.\n     *\n     * Optional, must be a positive integer if provided. Defaults to\n     * the value of `maxSize` if provided.\n     */\n    maxEntrySize?: Size\n\n    /**\n     * A function that returns a number indicating the item's size.\n     *\n     * Requires {@link OptionsBase.maxSize} to be set.\n     *\n     * If not provided, and {@link OptionsBase.maxSize} or\n     * {@link OptionsBase.maxEntrySize} are set, then all\n     * {@link LRUCache#set} calls **must** provide an explicit\n     * {@link SetOptions.size} or sizeCalculation param.\n     */\n    sizeCalculation?: SizeCalculator\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#fetch}\n     *\n     * ```ts\n     * fetchMethod(key, staleValue, { signal, options, context })\n     * ```\n     *\n     * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n     * to `Promise.resolve(cache.get(key))`.\n     *\n     * If at any time, `signal.aborted` is set to `true`, or if the\n     * `signal.onabort` method is called, or if it emits an `'abort'` event\n     * which you can listen to with `addEventListener`, then that means that\n     * the fetch should be abandoned. This may be passed along to async\n     * functions aware of AbortController/AbortSignal behavior.\n     *\n     * The `fetchMethod` should **only** return `undefined` or a Promise\n     * resolving to `undefined` if the AbortController signaled an `abort`\n     * event. In all other cases, it should return or resolve to a value\n     * suitable for adding to the cache.\n     *\n     * The `options` object is a union of the options that may be provided to\n     * `set()` and `get()`. If they are modified, then that will result in\n     * modifying the settings to `cache.set()` when the value is resolved, and\n     * in the case of\n     * {@link OptionsBase.noDeleteOnFetchRejection} and\n     * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n     * `fetchMethod` failures.\n     *\n     * For example, a DNS cache may update the TTL based on the value returned\n     * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n     */\n    fetchMethod?: Fetcher\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#memo}\n     */\n    memoMethod?: Memoizer\n\n    /**\n     * Set to true to suppress the deletion of stale data when a\n     * {@link OptionsBase.fetchMethod} returns a rejected promise.\n     */\n    noDeleteOnFetchRejection?: boolean\n\n    /**\n     * Do not delete stale items when they are retrieved with\n     * {@link LRUCache#get}.\n     *\n     * Note that the `get` return value will still be `undefined`\n     * unless {@link OptionsBase.allowStale} is true.\n     *\n     * When using time-expiring entries with `ttl`, by default stale\n     * items will be removed from the cache when the key is accessed\n     * with `cache.get()`.\n     *\n     * Setting this option will cause stale items to remain in the cache, until\n     * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n     * `noDeleteOnStaleGet` set to `false`.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     *\n     * Only relevant if a ttl is used.\n     */\n    noDeleteOnStaleGet?: boolean\n\n    /**\n     * Set to true to allow returning stale data when a\n     * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n     * promise.\n     *\n     * This differs from using {@link OptionsBase.allowStale} in that stale\n     * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n     * fails, not any other times.\n     *\n     * If a `fetchMethod` fails, and there is no stale value available, the\n     * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n     * suppressed.\n     *\n     * Implies `noDeleteOnFetchRejection`.\n     *\n     * This may be set in calls to `fetch()`, or defaulted on the constructor,\n     * or overridden by modifying the options object in the `fetchMethod`.\n     */\n    allowStaleOnFetchRejection?: boolean\n\n    /**\n     * Set to true to return a stale value from the cache when the\n     * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n     * an `'abort'` event, whether user-triggered, or due to internal cache\n     * behavior.\n     *\n     * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n     * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n     * any value it returns will be ignored and not cached.\n     *\n     * Caveat: since fetches are aborted when a new value is explicitly\n     * set in the cache, this can lead to fetch returning a stale value,\n     * since that was the fallback value _at the moment the `fetch()` was\n     * initiated_, even though the new updated value is now present in\n     * the cache.\n     *\n     * For example:\n     *\n     * ```ts\n     * const cache = new LRUCache({\n     *   ttl: 100,\n     *   fetchMethod: async (url, oldValue, { signal }) =>  {\n     *     const res = await fetch(url, { signal })\n     *     return await res.json()\n     *   }\n     * })\n     * cache.set('https://example.com/', { some: 'data' })\n     * // 100ms go by...\n     * const result = cache.fetch('https://example.com/')\n     * cache.set('https://example.com/', { other: 'thing' })\n     * console.log(await result) // { some: 'data' }\n     * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n     * ```\n     */\n    allowStaleOnFetchAbort?: boolean\n\n    /**\n     * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n     * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n     * resulting resolution value, as long as it is not `undefined`.\n     *\n     * When used on its own, this means aborted {@link LRUCache#fetch} calls\n     * are not immediately resolved or rejected when they are aborted, and\n     * instead take the full time to await.\n     *\n     * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n     * {@link LRUCache#fetch} calls will resolve immediately to their stale\n     * cached value or `undefined`, and will continue to process and eventually\n     * update the cache when they resolve, as long as the resulting value is\n     * not `undefined`, thus supporting a \"return stale on timeout while\n     * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n     *\n     * For example:\n     *\n     * ```ts\n     * const c = new LRUCache({\n     *   ttl: 100,\n     *   ignoreFetchAbort: true,\n     *   allowStaleOnFetchAbort: true,\n     *   fetchMethod: async (key, oldValue, { signal }) => {\n     *     // note: do NOT pass the signal to fetch()!\n     *     // let's say this fetch can take a long time.\n     *     const res = await fetch(`https://slow-backend-server/${key}`)\n     *     return await res.json()\n     *   },\n     * })\n     *\n     * // this will return the stale value after 100ms, while still\n     * // updating in the background for next time.\n     * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n     * ```\n     *\n     * **Note**: regardless of this setting, an `abort` event _is still\n     * emitted on the `AbortSignal` object_, so may result in invalid results\n     * when passed to other underlying APIs that use AbortSignals.\n     *\n     * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n     * call to {@link LRUCache#fetch}.\n     */\n    ignoreFetchAbort?: boolean\n\n    /**\n     * In some cases, you may want to swap out the performance/Date object\n     * used for TTL tracking. This should almost certainly NOT be done in\n     * production environments!\n     *\n     * This value defaults to `global.performance` if it has a `now()` method,\n     * or the `global.Date` object otherwise.\n     */\n    perf?: Perf\n  }\n\n  export interface OptionsMaxLimit\n    extends OptionsBase {\n    max: Count\n  }\n  export interface OptionsTTLLimit\n    extends OptionsBase {\n    ttl: Milliseconds\n    ttlAutopurge: boolean\n  }\n  export interface OptionsSizeLimit\n    extends OptionsBase {\n    maxSize: Size\n  }\n\n  /**\n   * The valid safe options for the {@link LRUCache} constructor\n   */\n  export type Options =\n    | OptionsMaxLimit\n    | OptionsSizeLimit\n    | OptionsTTLLimit\n\n  /**\n   * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n   * and returned by {@link LRUCache#info}.\n   */\n  export interface Entry {\n    value: V\n    ttl?: Milliseconds\n    size?: Size\n    start?: Milliseconds\n  }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache {\n  // options that cannot be changed without disaster\n  readonly #max: LRUCache.Count\n  readonly #maxSize: LRUCache.Size\n  readonly #dispose?: LRUCache.Disposer\n  readonly #onInsert?: LRUCache.Inserter\n  readonly #disposeAfter?: LRUCache.Disposer\n  readonly #fetchMethod?: LRUCache.Fetcher\n  readonly #memoMethod?: LRUCache.Memoizer\n  readonly #perf: Perf\n\n  /**\n   * {@link LRUCache.OptionsBase.perf}\n   */\n  get perf() {\n    return this.#perf\n  }\n\n  /**\n   * {@link LRUCache.OptionsBase.ttl}\n   */\n  ttl: LRUCache.Milliseconds\n\n  /**\n   * {@link LRUCache.OptionsBase.ttlResolution}\n   */\n  ttlResolution: LRUCache.Milliseconds\n  /**\n   * {@link LRUCache.OptionsBase.ttlAutopurge}\n   */\n  ttlAutopurge: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnGet}\n   */\n  updateAgeOnGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnHas}\n   */\n  updateAgeOnHas: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStale}\n   */\n  allowStale: boolean\n\n  /**\n   * {@link LRUCache.OptionsBase.noDisposeOnSet}\n   */\n  noDisposeOnSet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noUpdateTTL}\n   */\n  noUpdateTTL: boolean\n  /**\n   * {@link LRUCache.OptionsBase.maxEntrySize}\n   */\n  maxEntrySize: LRUCache.Size\n  /**\n   * {@link LRUCache.OptionsBase.sizeCalculation}\n   */\n  sizeCalculation?: LRUCache.SizeCalculator\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n   */\n  noDeleteOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n   */\n  noDeleteOnStaleGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n   */\n  allowStaleOnFetchAbort: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n   */\n  allowStaleOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n   */\n  ignoreFetchAbort: boolean\n\n  // computed properties\n  #size: LRUCache.Count\n  #calculatedSize: LRUCache.Size\n  #keyMap: Map\n  #keyList: (K | undefined)[]\n  #valList: (V | BackgroundFetch | undefined)[]\n  #next: NumberArray\n  #prev: NumberArray\n  #head: Index\n  #tail: Index\n  #free: StackLike\n  #disposed?: DisposeTask[]\n  #sizes?: ZeroArray\n  #starts?: ZeroArray\n  #ttls?: ZeroArray\n  #autopurgeTimers?: (undefined | ReturnType)[]\n\n  #hasDispose: boolean\n  #hasFetchMethod: boolean\n  #hasDisposeAfter: boolean\n  #hasOnInsert: boolean\n\n  /**\n   * Do not call this method unless you need to inspect the\n   * inner workings of the cache.  If anything returned by this\n   * object is modified in any way, strange breakage may occur.\n   *\n   * These fields are private for a reason!\n   *\n   * @internal\n   */\n  static unsafeExposeInternals<\n    K extends {},\n    V extends {},\n    FC extends unknown = unknown,\n  >(c: LRUCache) {\n    return {\n      // properties\n      starts: c.#starts,\n      ttls: c.#ttls,\n      autopurgeTimers: c.#autopurgeTimers,\n      sizes: c.#sizes,\n      keyMap: c.#keyMap as Map,\n      keyList: c.#keyList,\n      valList: c.#valList,\n      next: c.#next,\n      prev: c.#prev,\n      get head() {\n        return c.#head\n      },\n      get tail() {\n        return c.#tail\n      },\n      free: c.#free,\n      // methods\n      isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n      backgroundFetch: (\n        k: K,\n        index: number | undefined,\n        options: LRUCache.FetchOptions,\n        context: any,\n      ): BackgroundFetch =>\n        c.#backgroundFetch(\n          k,\n          index as Index | undefined,\n          options,\n          context,\n        ),\n      moveToTail: (index: number): void => c.#moveToTail(index as Index),\n      indexes: (options?: { allowStale: boolean }) => c.#indexes(options),\n      rindexes: (options?: { allowStale: boolean }) =>\n        c.#rindexes(options),\n      isStale: (index: number | undefined) => c.#isStale(index as Index),\n    }\n  }\n\n  // Protected read-only members\n\n  /**\n   * {@link LRUCache.OptionsBase.max} (read-only)\n   */\n  get max(): LRUCache.Count {\n    return this.#max\n  }\n  /**\n   * {@link LRUCache.OptionsBase.maxSize} (read-only)\n   */\n  get maxSize(): LRUCache.Count {\n    return this.#maxSize\n  }\n  /**\n   * The total computed size of items in the cache (read-only)\n   */\n  get calculatedSize(): LRUCache.Size {\n    return this.#calculatedSize\n  }\n  /**\n   * The number of items stored in the cache (read-only)\n   */\n  get size(): LRUCache.Count {\n    return this.#size\n  }\n  /**\n   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n   */\n  get fetchMethod(): LRUCache.Fetcher | undefined {\n    return this.#fetchMethod\n  }\n  get memoMethod(): LRUCache.Memoizer | undefined {\n    return this.#memoMethod\n  }\n  /**\n   * {@link LRUCache.OptionsBase.dispose} (read-only)\n   */\n  get dispose() {\n    return this.#dispose\n  }\n  /**\n   * {@link LRUCache.OptionsBase.onInsert} (read-only)\n   */\n  get onInsert() {\n    return this.#onInsert\n  }\n  /**\n   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n   */\n  get disposeAfter() {\n    return this.#disposeAfter\n  }\n\n  constructor(options: LRUCache.Options | LRUCache) {\n    const {\n      max = 0,\n      ttl,\n      ttlResolution = 1,\n      ttlAutopurge,\n      updateAgeOnGet,\n      updateAgeOnHas,\n      allowStale,\n      dispose,\n      onInsert,\n      disposeAfter,\n      noDisposeOnSet,\n      noUpdateTTL,\n      maxSize = 0,\n      maxEntrySize = 0,\n      sizeCalculation,\n      fetchMethod,\n      memoMethod,\n      noDeleteOnFetchRejection,\n      noDeleteOnStaleGet,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      perf,\n    } = options\n\n    if (perf !== undefined) {\n      if (typeof perf?.now !== 'function') {\n        throw new TypeError(\n          'perf option must have a now() method if specified',\n        )\n      }\n    }\n\n    this.#perf = perf ?? defaultPerf\n\n    if (max !== 0 && !isPosInt(max)) {\n      throw new TypeError('max option must be a nonnegative integer')\n    }\n\n    const UintArray = max ? getUintArray(max) : Array\n    if (!UintArray) {\n      throw new Error('invalid max value: ' + max)\n    }\n\n    this.#max = max\n    this.#maxSize = maxSize\n    this.maxEntrySize = maxEntrySize || this.#maxSize\n    this.sizeCalculation = sizeCalculation\n    if (this.sizeCalculation) {\n      if (!this.#maxSize && !this.maxEntrySize) {\n        throw new TypeError(\n          'cannot set sizeCalculation without setting maxSize or maxEntrySize',\n        )\n      }\n      if (typeof this.sizeCalculation !== 'function') {\n        throw new TypeError('sizeCalculation set to non-function')\n      }\n    }\n\n    if (memoMethod !== undefined && typeof memoMethod !== 'function') {\n      throw new TypeError('memoMethod must be a function if defined')\n    }\n    this.#memoMethod = memoMethod\n\n    if (fetchMethod !== undefined && typeof fetchMethod !== 'function') {\n      throw new TypeError('fetchMethod must be a function if specified')\n    }\n    this.#fetchMethod = fetchMethod\n    this.#hasFetchMethod = !!fetchMethod\n\n    this.#keyMap = new Map()\n    this.#keyList = new Array(max).fill(undefined)\n    this.#valList = new Array(max).fill(undefined)\n    this.#next = new UintArray(max)\n    this.#prev = new UintArray(max)\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free = Stack.create(max)\n    this.#size = 0\n    this.#calculatedSize = 0\n\n    if (typeof dispose === 'function') {\n      this.#dispose = dispose\n    }\n    if (typeof onInsert === 'function') {\n      this.#onInsert = onInsert\n    }\n    if (typeof disposeAfter === 'function') {\n      this.#disposeAfter = disposeAfter\n      this.#disposed = []\n    } else {\n      this.#disposeAfter = undefined\n      this.#disposed = undefined\n    }\n    this.#hasDispose = !!this.#dispose\n    this.#hasOnInsert = !!this.#onInsert\n    this.#hasDisposeAfter = !!this.#disposeAfter\n\n    this.noDisposeOnSet = !!noDisposeOnSet\n    this.noUpdateTTL = !!noUpdateTTL\n    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n    this.ignoreFetchAbort = !!ignoreFetchAbort\n\n    // NB: maxEntrySize is set to maxSize if it's set\n    if (this.maxEntrySize !== 0) {\n      if (this.#maxSize !== 0) {\n        if (!isPosInt(this.#maxSize)) {\n          throw new TypeError(\n            'maxSize must be a positive integer if specified',\n          )\n        }\n      }\n      if (!isPosInt(this.maxEntrySize)) {\n        throw new TypeError(\n          'maxEntrySize must be a positive integer if specified',\n        )\n      }\n      this.#initializeSizeTracking()\n    }\n\n    this.allowStale = !!allowStale\n    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n    this.updateAgeOnGet = !!updateAgeOnGet\n    this.updateAgeOnHas = !!updateAgeOnHas\n    this.ttlResolution =\n      isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1\n    this.ttlAutopurge = !!ttlAutopurge\n    this.ttl = ttl || 0\n    if (this.ttl) {\n      if (!isPosInt(this.ttl)) {\n        throw new TypeError('ttl must be a positive integer if specified')\n      }\n      this.#initializeTTLTracking()\n    }\n\n    // do not allow completely unbounded caches\n    if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n      throw new TypeError(\n        'At least one of max, maxSize, or ttl is required',\n      )\n    }\n    if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n      const code = 'LRU_CACHE_UNBOUNDED'\n      if (shouldWarn(code)) {\n        warned.add(code)\n        const msg =\n          'TTL caching without ttlAutopurge, max, or maxSize can ' +\n          'result in unbounded memory consumption.'\n        emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n      }\n    }\n  }\n\n  /**\n   * Return the number of ms left in the item's TTL. If item is not in cache,\n   * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n   */\n  getRemainingTTL(key: K) {\n    return this.#keyMap.has(key) ? Infinity : 0\n  }\n\n  #initializeTTLTracking() {\n    const ttls = new ZeroArray(this.#max)\n    const starts = new ZeroArray(this.#max)\n    this.#ttls = ttls\n    this.#starts = starts\n    const purgeTimers =\n      this.ttlAutopurge ?\n        new Array>(this.#max)\n      : undefined\n    this.#autopurgeTimers = purgeTimers\n\n    this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {\n      starts[index] = ttl !== 0 ? start : 0\n      ttls[index] = ttl\n      // clear out the purge timer if we're setting TTL to 0, and\n      // previously had a ttl purge timer running, so it doesn't\n      // fire unnecessarily.\n      if (purgeTimers?.[index]) {\n        clearTimeout(purgeTimers[index])\n        purgeTimers[index] = undefined\n      }\n      if (ttl !== 0 && purgeTimers) {\n        const t = setTimeout(() => {\n          if (this.#isStale(index)) {\n            this.#delete(this.#keyList[index] as K, 'expire')\n          }\n        }, ttl + 1)\n        // unref() not supported on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n        purgeTimers[index] = t\n      }\n    }\n\n    this.#updateItemAge = index => {\n      starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0\n    }\n\n    this.#statusTTL = (status, index) => {\n      if (ttls[index]) {\n        const ttl = ttls[index]\n        const start = starts[index]\n        /* c8 ignore next */\n        if (!ttl || !start) return\n        status.ttl = ttl\n        status.start = start\n        status.now = cachedNow || getNow()\n        const age = status.now - start\n        status.remainingTTL = ttl - age\n      }\n    }\n\n    // debounce calls to perf.now() to 1s so we're not hitting\n    // that costly call repeatedly.\n    let cachedNow = 0\n    const getNow = () => {\n      const n = this.#perf.now()\n      if (this.ttlResolution > 0) {\n        cachedNow = n\n        const t = setTimeout(() => (cachedNow = 0), this.ttlResolution)\n        // not available on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n      return n\n    }\n\n    this.getRemainingTTL = key => {\n      const index = this.#keyMap.get(key)\n      if (index === undefined) {\n        return 0\n      }\n      const ttl = ttls[index]\n      const start = starts[index]\n      if (!ttl || !start) {\n        return Infinity\n      }\n      const age = (cachedNow || getNow()) - start\n      return ttl - age\n    }\n\n    this.#isStale = index => {\n      const s = starts[index]\n      const t = ttls[index]\n      return !!t && !!s && (cachedNow || getNow()) - s > t\n    }\n  }\n\n  // conditionally set private methods related to TTL\n  #updateItemAge: (index: Index) => void = () => {}\n  #statusTTL: (status: LRUCache.Status, index: Index) => void = () => {}\n  #setItemTTL: (\n    index: Index,\n    ttl: LRUCache.Milliseconds,\n    start?: LRUCache.Milliseconds,\n    // ignore because we never call this if we're not already in TTL mode\n    /* c8 ignore start */\n  ) => void = () => {}\n  /* c8 ignore stop */\n\n  #isStale: (index: Index) => boolean = () => false\n\n  #initializeSizeTracking() {\n    const sizes = new ZeroArray(this.#max)\n    this.#calculatedSize = 0\n    this.#sizes = sizes\n    this.#removeItemSize = index => {\n      this.#calculatedSize -= sizes[index] as number\n      sizes[index] = 0\n    }\n    this.#requireSize = (k, v, size, sizeCalculation) => {\n      // provisionally accept background fetches.\n      // actual value size will be checked when they return.\n      if (this.#isBackgroundFetch(v)) {\n        return 0\n      }\n      if (!isPosInt(size)) {\n        if (sizeCalculation) {\n          if (typeof sizeCalculation !== 'function') {\n            throw new TypeError('sizeCalculation must be a function')\n          }\n          size = sizeCalculation(v, k)\n          if (!isPosInt(size)) {\n            throw new TypeError(\n              'sizeCalculation return invalid (expect positive integer)',\n            )\n          }\n        } else {\n          throw new TypeError(\n            'invalid size value (must be positive integer). ' +\n              'When maxSize or maxEntrySize is used, sizeCalculation ' +\n              'or size must be set.',\n          )\n        }\n      }\n      return size\n    }\n    this.#addItemSize = (\n      index: Index,\n      size: LRUCache.Size,\n      status?: LRUCache.Status,\n    ) => {\n      sizes[index] = size\n      if (this.#maxSize) {\n        const maxSize = this.#maxSize - (sizes[index] as number)\n        while (this.#calculatedSize > maxSize) {\n          this.#evict(true)\n        }\n      }\n      this.#calculatedSize += sizes[index] as number\n      if (status) {\n        status.entrySize = size\n        status.totalCalculatedSize = this.#calculatedSize\n      }\n    }\n  }\n\n  #removeItemSize: (index: Index) => void = _i => {}\n  #addItemSize: (\n    index: Index,\n    size: LRUCache.Size,\n    status?: LRUCache.Status,\n  ) => void = (_i, _s, _st) => {}\n  #requireSize: (\n    k: K,\n    v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator,\n  ) => LRUCache.Size = (\n    _k: K,\n    _v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator,\n  ) => {\n    if (size || sizeCalculation) {\n      throw new TypeError(\n        'cannot set size without setting maxSize or maxEntrySize on cache',\n      )\n    }\n    return 0\n  };\n\n  *#indexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#tail; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#head) {\n          break\n        } else {\n          i = this.#prev[i] as Index\n        }\n      }\n    }\n  }\n\n  *#rindexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#head; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#tail) {\n          break\n        } else {\n          i = this.#next[i] as Index\n        }\n      }\n    }\n  }\n\n  #isValidIndex(index: Index) {\n    return (\n      index !== undefined &&\n      this.#keyMap.get(this.#keyList[index] as K) === index\n    )\n  }\n\n  /**\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from most recently used to least recently used.\n   */\n  *entries() {\n    for (const i of this.#indexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]] as [K, V]\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.entries}\n   *\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from least recently used to most recently used.\n   */\n  *rentries() {\n    for (const i of this.#rindexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]]\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the keys in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *keys() {\n    for (const i of this.#indexes()) {\n      const k = this.#keyList[i]\n      if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.keys}\n   *\n   * Return a generator yielding the keys in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rkeys() {\n    for (const i of this.#rindexes()) {\n      const k = this.#keyList[i]\n      if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the values in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *values() {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield this.#valList[i] as V\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.values}\n   *\n   * Return a generator yielding the values in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rvalues() {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield this.#valList[i]\n      }\n    }\n  }\n\n  /**\n   * Iterating over the cache itself yields the same results as\n   * {@link LRUCache.entries}\n   */\n  [Symbol.iterator]() {\n    return this.entries()\n  }\n\n  /**\n   * A String value that is used in the creation of the default string\n   * description of an object. Called by the built-in method\n   * `Object.prototype.toString`.\n   */\n  [Symbol.toStringTag] = 'LRUCache'\n\n  /**\n   * Find a value for which the supplied fn method returns a truthy value,\n   * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n   */\n  find(\n    fn: (v: V, k: K, self: LRUCache) => boolean,\n    getOptions: LRUCache.GetOptions = {},\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      if (fn(value, this.#keyList[i] as K, this)) {\n        return this.get(this.#keyList[i] as K, getOptions)\n      }\n    }\n  }\n\n  /**\n   * Call the supplied function on each item in the cache, in order from most\n   * recently used to least recently used.\n   *\n   * `fn` is called as `fn(value, key, cache)`.\n   *\n   * If `thisp` is provided, function will be called in the `this`-context of\n   * the provided object, or the cache if no `thisp` object is provided.\n   *\n   * Does not update age or recenty of use, or iterate over stale values.\n   */\n  forEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this,\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * The same as {@link LRUCache.forEach} but items are iterated over in\n   * reverse order.  (ie, less recently used items are iterated over first.)\n   */\n  rforEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this,\n  ) {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * Delete any stale entries. Returns true if anything was removed,\n   * false otherwise.\n   */\n  purgeStale() {\n    let deleted = false\n    for (const i of this.#rindexes({ allowStale: true })) {\n      if (this.#isStale(i)) {\n        this.#delete(this.#keyList[i] as K, 'expire')\n        deleted = true\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Get the extended info about a given entry, to get its value, size, and\n   * TTL info simultaneously. Returns `undefined` if the key is not present.\n   *\n   * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n   * serialization, the `start` value is always the current timestamp, and the\n   * `ttl` is a calculated remaining time to live (negative if expired).\n   *\n   * Always returns stale values, if their info is found in the cache, so be\n   * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n   * if relevant.\n   */\n  info(key: K): LRUCache.Entry | undefined {\n    const i = this.#keyMap.get(key)\n    if (i === undefined) return undefined\n    const v = this.#valList[i]\n    /* c8 ignore start - this isn't tested for the info function,\n     * but it's the same logic as found in other places. */\n    const value: V | undefined =\n      this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n    if (value === undefined) return undefined\n    /* c8 ignore end */\n    const entry: LRUCache.Entry = { value }\n    if (this.#ttls && this.#starts) {\n      const ttl = this.#ttls[i]\n      const start = this.#starts[i]\n      if (ttl && start) {\n        const remain = ttl - (this.#perf.now() - start)\n        entry.ttl = remain\n        entry.start = Date.now()\n      }\n    }\n    if (this.#sizes) {\n      entry.size = this.#sizes[i]\n    }\n    return entry\n  }\n\n  /**\n   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n   * passed to {@link LRUCache#load}.\n   *\n   * The `start` fields are calculated relative to a portable `Date.now()`\n   * timestamp, even if `performance.now()` is available.\n   *\n   * Stale entries are always included in the `dump`, even if\n   * {@link LRUCache.OptionsBase.allowStale} is false.\n   *\n   * Note: this returns an actual array, not a generator, so it can be more\n   * easily passed around.\n   */\n  dump() {\n    const arr: [K, LRUCache.Entry][] = []\n    for (const i of this.#indexes({ allowStale: true })) {\n      const key = this.#keyList[i]\n      const v = this.#valList[i]\n      const value: V | undefined =\n        this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined || key === undefined) continue\n      const entry: LRUCache.Entry = { value }\n      if (this.#ttls && this.#starts) {\n        entry.ttl = this.#ttls[i]\n        // always dump the start relative to a portable timestamp\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = this.#perf.now() - (this.#starts[i] as number)\n        entry.start = Math.floor(Date.now() - age)\n      }\n      if (this.#sizes) {\n        entry.size = this.#sizes[i]\n      }\n      arr.unshift([key, entry])\n    }\n    return arr\n  }\n\n  /**\n   * Reset the cache and load in the items in entries in the order listed.\n   *\n   * The shape of the resulting cache may be different if the same options are\n   * not used in both caches.\n   *\n   * The `start` fields are assumed to be calculated relative to a portable\n   * `Date.now()` timestamp, even if `performance.now()` is available.\n   */\n  load(arr: [K, LRUCache.Entry][]) {\n    this.clear()\n    for (const [key, entry] of arr) {\n      if (entry.start) {\n        // entry.start is a portable timestamp, but we may be using\n        // node's performance.now(), so calculate the offset, so that\n        // we get the intended remaining TTL, no matter how long it's\n        // been on ice.\n        //\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = Date.now() - entry.start\n        entry.start = this.#perf.now() - age\n      }\n      this.set(key, entry.value, entry)\n    }\n  }\n\n  /**\n   * Add a value to the cache.\n   *\n   * Note: if `undefined` is specified as a value, this is an alias for\n   * {@link LRUCache#delete}\n   *\n   * Fields on the {@link LRUCache.SetOptions} options param will override\n   * their corresponding values in the constructor options for the scope\n   * of this single `set()` operation.\n   *\n   * If `start` is provided, then that will set the effective start\n   * time for the TTL calculation. Note that this must be a previous\n   * value of `performance.now()` if supported, or a previous value of\n   * `Date.now()` if not.\n   *\n   * Options object may also include `size`, which will prevent\n   * calling the `sizeCalculation` function and just use the specified\n   * number if it is a positive integer, and `noDisposeOnSet` which\n   * will prevent calling a `dispose` function in the case of\n   * overwrites.\n   *\n   * If the `size` (or return value of `sizeCalculation`) for a given\n   * entry is greater than `maxEntrySize`, then the item will not be\n   * added to the cache.\n   *\n   * Will update the recency of the entry.\n   *\n   * If the value is `undefined`, then this is an alias for\n   * `cache.delete(key)`. `undefined` is never stored in the cache.\n   */\n  set(\n    k: K,\n    v: V | BackgroundFetch | undefined,\n    setOptions: LRUCache.SetOptions = {},\n  ) {\n    if (v === undefined) {\n      this.delete(k)\n      return this\n    }\n    const {\n      ttl = this.ttl,\n      start,\n      noDisposeOnSet = this.noDisposeOnSet,\n      sizeCalculation = this.sizeCalculation,\n      status,\n    } = setOptions\n    let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n    const size = this.#requireSize(\n      k,\n      v,\n      setOptions.size || 0,\n      sizeCalculation,\n    )\n    // if the item doesn't fit, don't do anything\n    // NB: maxEntrySize set to maxSize by default\n    if (this.maxEntrySize && size > this.maxEntrySize) {\n      if (status) {\n        status.set = 'miss'\n        status.maxEntrySizeExceeded = true\n      }\n      // have to delete, in case something is there already.\n      this.#delete(k, 'set')\n      return this\n    }\n    let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n    if (index === undefined) {\n      // addition\n      index = (\n        this.#size === 0 ? this.#tail\n        : this.#free.length !== 0 ? this.#free.pop()\n        : this.#size === this.#max ? this.#evict(false)\n        : this.#size) as Index\n      this.#keyList[index] = k\n      this.#valList[index] = v\n      this.#keyMap.set(k, index)\n      this.#next[this.#tail] = index\n      this.#prev[index] = this.#tail\n      this.#tail = index\n      this.#size++\n      this.#addItemSize(index, size, status)\n      if (status) status.set = 'add'\n      noUpdateTTL = false\n      if (this.#hasOnInsert) {\n        this.#onInsert?.(v as V, k, 'add')\n      }\n    } else {\n      // update\n      this.#moveToTail(index)\n      const oldVal = this.#valList[index] as V | BackgroundFetch\n      if (v !== oldVal) {\n        if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n          oldVal.__abortController.abort(new Error('replaced'))\n          const { __staleWhileFetching: s } = oldVal\n          if (s !== undefined && !noDisposeOnSet) {\n            if (this.#hasDispose) {\n              this.#dispose?.(s as V, k, 'set')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([s as V, k, 'set'])\n            }\n          }\n        } else if (!noDisposeOnSet) {\n          if (this.#hasDispose) {\n            this.#dispose?.(oldVal as V, k, 'set')\n          }\n          if (this.#hasDisposeAfter) {\n            this.#disposed?.push([oldVal as V, k, 'set'])\n          }\n        }\n        this.#removeItemSize(index)\n        this.#addItemSize(index, size, status)\n        this.#valList[index] = v\n        if (status) {\n          status.set = 'replace'\n          const oldValue =\n            oldVal && this.#isBackgroundFetch(oldVal) ?\n              oldVal.__staleWhileFetching\n            : oldVal\n          if (oldValue !== undefined) status.oldValue = oldValue\n        }\n      } else if (status) {\n        status.set = 'update'\n      }\n\n      if (this.#hasOnInsert) {\n        this.onInsert?.(v as V, k, v === oldVal ? 'update' : 'replace')\n      }\n    }\n    if (ttl !== 0 && !this.#ttls) {\n      this.#initializeTTLTracking()\n    }\n    if (this.#ttls) {\n      if (!noUpdateTTL) {\n        this.#setItemTTL(index, ttl, start)\n      }\n      if (status) this.#statusTTL(status, index)\n    }\n    if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return this\n  }\n\n  /**\n   * Evict the least recently used item, returning its value or\n   * `undefined` if cache is empty.\n   */\n  pop(): V | undefined {\n    try {\n      while (this.#size) {\n        const val = this.#valList[this.#head]\n        this.#evict(true)\n        if (this.#isBackgroundFetch(val)) {\n          if (val.__staleWhileFetching) {\n            return val.__staleWhileFetching\n          }\n        } else if (val !== undefined) {\n          return val\n        }\n      }\n    } finally {\n      if (this.#hasDisposeAfter && this.#disposed) {\n        const dt = this.#disposed\n        let task: DisposeTask | undefined\n        while ((task = dt?.shift())) {\n          this.#disposeAfter?.(...task)\n        }\n      }\n    }\n  }\n\n  #evict(free: boolean) {\n    const head = this.#head\n    const k = this.#keyList[head] as K\n    const v = this.#valList[head] as V\n    if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n      v.__abortController.abort(new Error('evicted'))\n    } else if (this.#hasDispose || this.#hasDisposeAfter) {\n      if (this.#hasDispose) {\n        this.#dispose?.(v, k, 'evict')\n      }\n      if (this.#hasDisposeAfter) {\n        this.#disposed?.push([v, k, 'evict'])\n      }\n    }\n    this.#removeItemSize(head)\n    if (this.#autopurgeTimers?.[head]) {\n      clearTimeout(this.#autopurgeTimers[head])\n      this.#autopurgeTimers[head] = undefined\n    }\n    // if we aren't about to use the index, then null these out\n    if (free) {\n      this.#keyList[head] = undefined\n      this.#valList[head] = undefined\n      this.#free.push(head)\n    }\n    if (this.#size === 1) {\n      this.#head = this.#tail = 0 as Index\n      this.#free.length = 0\n    } else {\n      this.#head = this.#next[head] as Index\n    }\n    this.#keyMap.delete(k)\n    this.#size--\n    return head\n  }\n\n  /**\n   * Check if a key is in the cache, without updating the recency of use.\n   * Will return false if the item is stale, even though it is technically\n   * in the cache.\n   *\n   * Check if a key is in the cache, without updating the recency of\n   * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n   * to `true` in either the options or the constructor.\n   *\n   * Will return `false` if the item is stale, even though it is technically in\n   * the cache. The difference can be determined (if it matters) by using a\n   * `status` argument, and inspecting the `has` field.\n   *\n   * Will not update item age unless\n   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n   */\n  has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const v = this.#valList[index]\n      if (\n        this.#isBackgroundFetch(v) &&\n        v.__staleWhileFetching === undefined\n      ) {\n        return false\n      }\n      if (!this.#isStale(index)) {\n        if (updateAgeOnHas) {\n          this.#updateItemAge(index)\n        }\n        if (status) {\n          status.has = 'hit'\n          this.#statusTTL(status, index)\n        }\n        return true\n      } else if (status) {\n        status.has = 'stale'\n        this.#statusTTL(status, index)\n      }\n    } else if (status) {\n      status.has = 'miss'\n    }\n    return false\n  }\n\n  /**\n   * Like {@link LRUCache#get} but doesn't update recency or delete stale\n   * items.\n   *\n   * Returns `undefined` if the item is stale, unless\n   * {@link LRUCache.OptionsBase.allowStale} is set.\n   */\n  peek(k: K, peekOptions: LRUCache.PeekOptions = {}) {\n    const { allowStale = this.allowStale } = peekOptions\n    const index = this.#keyMap.get(k)\n    if (index === undefined || (!allowStale && this.#isStale(index))) {\n      return\n    }\n    const v = this.#valList[index]\n    // either stale and allowed, or forcing a refresh of non-stale value\n    return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n  }\n\n  #backgroundFetch(\n    k: K,\n    index: Index | undefined,\n    options: LRUCache.FetchOptions,\n    context: any,\n  ): BackgroundFetch {\n    const v = index === undefined ? undefined : this.#valList[index]\n    if (this.#isBackgroundFetch(v)) {\n      return v\n    }\n\n    const ac = new AC()\n    const { signal } = options\n    // when/if our AC signals, then stop listening to theirs.\n    signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n      signal: ac.signal,\n    })\n\n    const fetchOpts = {\n      signal: ac.signal,\n      options,\n      context,\n    }\n\n    const cb = (v: V | undefined, updateCache = false): V | undefined => {\n      const { aborted } = ac.signal\n      const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n      const proceed = options.ignoreFetchAbort ||\n        !!(options.allowStaleOnFetchAbort && v !== undefined)\n      if (options.status) {\n        if (aborted && !updateCache) {\n          options.status.fetchAborted = true\n          options.status.fetchError = ac.signal.reason\n          if (ignoreAbort) options.status.fetchAbortIgnored = true\n        } else {\n          options.status.fetchResolved = true\n        }\n      }\n      if (aborted && !ignoreAbort && !updateCache) {\n        return fetchFail(ac.signal.reason, proceed)\n      }\n      // either we didn't abort, and are still here, or we did, and ignored\n      const bf = p as BackgroundFetch\n      // if nothing else has been written there but we're set to update the\n      // cache and ignore the abort, or if it's still pending on this specific\n      // background request, then write it to the cache.\n      const vl = this.#valList[index as Index]\n      if (vl === p || (ignoreAbort && updateCache && vl === undefined)) {\n        if (v === undefined) {\n          if (bf.__staleWhileFetching !== undefined) {\n            this.#valList[index as Index] = bf.__staleWhileFetching\n          } else {\n            this.#delete(k, 'fetch')\n          }\n        } else {\n          if (options.status) options.status.fetchUpdated = true\n          this.set(k, v, fetchOpts.options)\n        }\n      }\n      return v\n    }\n\n    const eb = (er: any) => {\n      if (options.status) {\n        options.status.fetchRejected = true\n        options.status.fetchError = er\n      }\n      // do not pass go, do not collect $200\n      return fetchFail(er, false)\n    }\n\n    const fetchFail = (er: any, proceed: boolean): V | undefined => {\n      const { aborted } = ac.signal\n      const allowStaleAborted = aborted && options.allowStaleOnFetchAbort\n      const allowStale =\n        allowStaleAborted || options.allowStaleOnFetchRejection\n      const noDelete = allowStale || options.noDeleteOnFetchRejection\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        // if we allow stale on fetch rejections, then we need to ensure that\n        // the stale value is not removed from the cache when the fetch fails.\n        const del = !noDelete ||\n          !proceed && bf.__staleWhileFetching === undefined\n        if (del) {\n          this.#delete(k, 'fetch')\n        } else if (!allowStaleAborted) {\n          // still replace the *promise* with the stale value,\n          // since we are done with the promise at this point.\n          // leave it untouched if we're still waiting for an\n          // aborted background fetch that hasn't yet returned.\n          this.#valList[index as Index] = bf.__staleWhileFetching\n        }\n      }\n      if (allowStale) {\n        if (options.status && bf.__staleWhileFetching !== undefined) {\n          options.status.returnedStale = true\n        }\n        return bf.__staleWhileFetching\n      } else if (bf.__returned === bf) {\n        throw er\n      }\n    }\n\n    const pcall = (\n      res: (v: V | undefined) => void,\n      rej: (e: any) => void,\n    ) => {\n      const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n      if (fmp && fmp instanceof Promise) {\n        fmp.then(v => res(v === undefined ? undefined : v), rej)\n      }\n      // ignored, we go until we finish, regardless.\n      // defer check until we are actually aborting,\n      // so fetchMethod can override.\n      ac.signal.addEventListener('abort', () => {\n        if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {\n          res(undefined)\n          // when it eventually resolves, update the cache.\n          if (options.allowStaleOnFetchAbort) {\n            res = v => cb(v, true)\n          }\n        }\n      })\n    }\n\n    if (options.status) options.status.fetchDispatched = true\n    const p = new Promise(pcall).then(cb, eb)\n    const bf: BackgroundFetch = Object.assign(p, {\n      __abortController: ac,\n      __staleWhileFetching: v,\n      __returned: undefined,\n    })\n\n    if (index === undefined) {\n      // internal, don't expose status.\n      this.set(k, bf, { ...fetchOpts.options, status: undefined })\n      index = this.#keyMap.get(k)\n    } else {\n      this.#valList[index] = bf\n    }\n    return bf\n  }\n\n  #isBackgroundFetch(p: any): p is BackgroundFetch {\n    if (!this.#hasFetchMethod) return false\n    const b = p as BackgroundFetch\n    return (\n      !!b &&\n      b instanceof Promise &&\n      b.hasOwnProperty('__staleWhileFetching') &&\n      b.__abortController instanceof AC\n    )\n  }\n\n  /**\n   * Make an asynchronous cached fetch using the\n   * {@link LRUCache.OptionsBase.fetchMethod} function.\n   *\n   * If the value is in the cache and not stale, then the returned\n   * Promise resolves to the value.\n   *\n   * If not in the cache, or beyond its TTL staleness, then\n   * `fetchMethod(key, staleValue, { options, signal, context })` is\n   * called, and the value returned will be added to the cache once\n   * resolved.\n   *\n   * If called with `allowStale`, and an asynchronous fetch is\n   * currently in progress to reload a stale value, then the former\n   * stale value will be returned.\n   *\n   * If called with `forceRefresh`, then the cached item will be\n   * re-fetched, even if it is not stale. However, if `allowStale` is also\n   * set, then the old value will still be returned. This is useful\n   * in cases where you want to force a reload of a cached value. If\n   * a background fetch is already in progress, then `forceRefresh`\n   * has no effect.\n   *\n   * If multiple fetches for the same key are issued, then they will all be\n   * coalesced into a single call to fetchMethod.\n   *\n   * Note that this means that handling options such as\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n   * {@link LRUCache.FetchOptions.signal},\n   * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n   * determined by the FIRST fetch() call for a given key.\n   *\n   * This is a known (fixable) shortcoming which will be addresed on when\n   * someone complains about it, as the fix would involve added complexity and\n   * may not be worth the costs for this edge case.\n   *\n   * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n   * effectively an alias for `Promise.resolve(cache.get(key))`.\n   *\n   * When the fetch method resolves to a value, if the fetch has not\n   * been aborted due to deletion, eviction, or being overwritten,\n   * then it is added to the cache using the options provided.\n   *\n   * If the key is evicted or deleted before the `fetchMethod`\n   * resolves, then the AbortSignal passed to the `fetchMethod` will\n   * receive an `abort` event, and the promise returned by `fetch()`\n   * will reject with the reason for the abort.\n   *\n   * If a `signal` is passed to the `fetch()` call, then aborting the\n   * signal will abort the fetch and cause the `fetch()` promise to\n   * reject with the reason provided.\n   *\n   * **Setting `context`**\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the {@link LRUCache} constructor, then all\n   * calls to `cache.fetch()` _must_ provide a `context` option. If\n   * set to `undefined` or `void`, then calls to fetch _must not_\n   * provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that\n   * might be relevant in the course of fetching the data. It is only\n   * relevant for the course of a single `fetch()` operation, and\n   * discarded afterwards.\n   *\n   * **Note: `fetch()` calls are inflight-unique**\n   *\n   * If you call `fetch()` multiple times with the same key value,\n   * then every call after the first will resolve on the same\n   * promise1,\n   * _even if they have different settings that would otherwise change\n   * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n   * or `ignoreFetchAbort`.\n   *\n   * In most cases, this is not a problem (in fact, only fetching\n   * something once is what you probably want, if you're caching in\n   * the first place). If you are changing the fetch() options\n   * dramatically between runs, there's a good chance that you might\n   * be trying to fit divergent semantics into a single object, and\n   * would be better off with multiple cache instances.\n   *\n   * **1**: Ie, they're not the \"same Promise\", but they resolve at\n   * the same time, because they're both waiting on the same\n   * underlying fetchMethod response.\n   */\n\n  fetch(\n    k: K,\n    fetchOptions: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n    : LRUCache.FetchOptionsWithContext,\n  ): Promise\n\n  // this overload not allowed if context is required\n  fetch(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    fetchOptions?: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n    : never,\n  ): Promise\n\n  async fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const {\n      // get options\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      // set options\n      ttl = this.ttl,\n      noDisposeOnSet = this.noDisposeOnSet,\n      size = 0,\n      sizeCalculation = this.sizeCalculation,\n      noUpdateTTL = this.noUpdateTTL,\n      // fetch exclusive options\n      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n      ignoreFetchAbort = this.ignoreFetchAbort,\n      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n      context,\n      forceRefresh = false,\n      status,\n      signal,\n    } = fetchOptions\n\n    if (!this.#hasFetchMethod) {\n      if (status) status.fetch = 'get'\n      return this.get(k, {\n        allowStale,\n        updateAgeOnGet,\n        noDeleteOnStaleGet,\n        status,\n      })\n    }\n\n    const options = {\n      allowStale,\n      updateAgeOnGet,\n      noDeleteOnStaleGet,\n      ttl,\n      noDisposeOnSet,\n      size,\n      sizeCalculation,\n      noUpdateTTL,\n      noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      status,\n      signal,\n    }\n\n    let index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.fetch = 'miss'\n      const p = this.#backgroundFetch(k, index, options, context)\n      return (p.__returned = p)\n    } else {\n      // in cache, maybe already fetching\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        const stale = allowStale && v.__staleWhileFetching !== undefined\n        if (status) {\n          status.fetch = 'inflight'\n          if (stale) status.returnedStale = true\n        }\n        return stale ? v.__staleWhileFetching : (v.__returned = v)\n      }\n\n      // if we force a refresh, that means do NOT serve the cached value,\n      // unless we are already in the process of refreshing the cache.\n      const isStale = this.#isStale(index)\n      if (!forceRefresh && !isStale) {\n        if (status) status.fetch = 'hit'\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        if (status) this.#statusTTL(status, index)\n        return v\n      }\n\n      // ok, it is stale or a forced refresh, and not already fetching.\n      // refresh the cache.\n      const p = this.#backgroundFetch(k, index, options, context)\n      const hasStale = p.__staleWhileFetching !== undefined\n      const staleVal = hasStale && allowStale\n      if (status) {\n        status.fetch = isStale ? 'stale' : 'refresh'\n        if (staleVal && isStale) status.returnedStale = true\n      }\n      return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n    }\n  }\n\n  /**\n   * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n   * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n   * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n   * because `ignoreFetchAbort` was specified (either to the constructor or\n   * in the {@link LRUCache.FetchOptions}). Also, the\n   * {@link LRUCache.OptionsBase.fetchMethod} may return `undefined` or `void`, making\n   * the test even more complicated.\n   *\n   * Because inferring the cases where `undefined` might be returned are so\n   * cumbersome, but testing for `undefined` can also be annoying, this method\n   * can be used, which will reject if `this.fetch()` resolves to undefined.\n   */\n  forceFetch(\n    k: K,\n    fetchOptions: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n    : LRUCache.FetchOptionsWithContext,\n  ): Promise\n  // this overload not allowed if context is required\n  forceFetch(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    fetchOptions?: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n    : never,\n  ): Promise\n  async forceFetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const v = await this.fetch(\n      k,\n      fetchOptions as unknown extends FC ? LRUCache.FetchOptions\n      : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n      : LRUCache.FetchOptionsWithContext,\n    )\n    if (v === undefined) throw new Error('fetch() returned undefined')\n    return v\n  }\n\n  /**\n   * If the key is found in the cache, then this is equivalent to\n   * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n   * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n   * _must_ provide a `context` option. If set to `undefined` or `void`, then\n   * calls to memo _must not_ provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that might be\n   * relevant in the course of fetching the data. It is only relevant for the\n   * course of a single `memo()` operation, and discarded afterwards.\n   */\n  memo(\n    k: K,\n    memoOptions: unknown extends FC ? LRUCache.MemoOptions\n    : FC extends undefined | void ? LRUCache.MemoOptionsNoContext\n    : LRUCache.MemoOptionsWithContext,\n  ): V\n  // this overload not allowed if context is required\n  memo(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    memoOptions?: unknown extends FC ? LRUCache.MemoOptions\n    : FC extends undefined | void ? LRUCache.MemoOptionsNoContext\n    : never,\n  ): V\n  memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n    const memoMethod = this.#memoMethod\n    if (!memoMethod) {\n      throw new Error('no memoMethod provided to constructor')\n    }\n    const { context, forceRefresh, ...options } = memoOptions\n    const v = this.get(k, options)\n    if (!forceRefresh && v !== undefined) return v\n    const vv = memoMethod(k, v, {\n      options,\n      context,\n    } as LRUCache.MemoizerOptions)\n    this.set(k, vv, options)\n    return vv\n  }\n\n  /**\n   * Return a value from the cache. Will update the recency of the cache\n   * entry found.\n   *\n   * If the key is not found, get() will return `undefined`.\n   */\n  get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const {\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      status,\n    } = getOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const value = this.#valList[index]\n      const fetching = this.#isBackgroundFetch(value)\n      if (status) this.#statusTTL(status, index)\n      if (this.#isStale(index)) {\n        if (status) status.get = 'stale'\n        // delete only if not an in-flight background fetch\n        if (!fetching) {\n          if (!noDeleteOnStaleGet) {\n            this.#delete(k, 'expire')\n          }\n          if (status && allowStale) status.returnedStale = true\n          return allowStale ? value : undefined\n        } else {\n          if (\n            status &&\n            allowStale &&\n            value.__staleWhileFetching !== undefined\n          ) {\n            status.returnedStale = true\n          }\n          return allowStale ? value.__staleWhileFetching : undefined\n        }\n      } else {\n        if (status) status.get = 'hit'\n        // if we're currently fetching it, we don't actually have it yet\n        // it's not stale, which means this isn't a staleWhileRefetching.\n        // If it's not stale, and fetching, AND has a __staleWhileFetching\n        // value, then that means the user fetched with {forceRefresh:true},\n        // so it's safe to return that value.\n        if (fetching) {\n          return value.__staleWhileFetching\n        }\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        return value\n      }\n    } else if (status) {\n      status.get = 'miss'\n    }\n  }\n\n  #connect(p: Index, n: Index) {\n    this.#prev[n] = p\n    this.#next[p] = n\n  }\n\n  #moveToTail(index: Index): void {\n    // if tail already, nothing to do\n    // if head, move head to next[index]\n    // else\n    //   move next[prev[index]] to next[index] (head has no prev)\n    //   move prev[next[index]] to prev[index]\n    // prev[index] = tail\n    // next[tail] = index\n    // tail = index\n    if (index !== this.#tail) {\n      if (index === this.#head) {\n        this.#head = this.#next[index] as Index\n      } else {\n        this.#connect(\n          this.#prev[index] as Index,\n          this.#next[index] as Index,\n        )\n      }\n      this.#connect(this.#tail, index)\n      this.#tail = index\n    }\n  }\n\n  /**\n   * Deletes a key out of the cache.\n   *\n   * Returns true if the key was deleted, false otherwise.\n   */\n  delete(k: K) {\n    return this.#delete(k, 'delete')\n  }\n\n  #delete(k: K, reason: LRUCache.DisposeReason) {\n    let deleted = false\n    if (this.#size !== 0) {\n      const index = this.#keyMap.get(k)\n      if (index !== undefined) {\n        if (this.#autopurgeTimers?.[index]) {\n          clearTimeout(this.#autopurgeTimers?.[index])\n          this.#autopurgeTimers[index] = undefined\n        }\n        deleted = true\n        if (this.#size === 1) {\n          this.#clear(reason)\n        } else {\n          this.#removeItemSize(index)\n          const v = this.#valList[index]\n          if (this.#isBackgroundFetch(v)) {\n            v.__abortController.abort(new Error('deleted'))\n          } else if (this.#hasDispose || this.#hasDisposeAfter) {\n            if (this.#hasDispose) {\n              this.#dispose?.(v as V, k, reason)\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([v as V, k, reason])\n            }\n          }\n          this.#keyMap.delete(k)\n          this.#keyList[index] = undefined\n          this.#valList[index] = undefined\n          if (index === this.#tail) {\n            this.#tail = this.#prev[index] as Index\n          } else if (index === this.#head) {\n            this.#head = this.#next[index] as Index\n          } else {\n            const pi = this.#prev[index] as number\n            this.#next[pi] = this.#next[index] as number\n            const ni = this.#next[index] as number\n            this.#prev[ni] = this.#prev[index] as number\n          }\n          this.#size--\n          this.#free.push(index)\n        }\n      }\n    }\n    if (this.#hasDisposeAfter && this.#disposed?.length) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Clear the cache entirely, throwing away all values.\n   */\n  clear() {\n    return this.#clear('delete')\n  }\n  #clear(reason: LRUCache.DisposeReason) {\n    for (const index of this.#rindexes({ allowStale: true })) {\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        v.__abortController.abort(new Error('deleted'))\n      } else {\n        const k = this.#keyList[index]\n        if (this.#hasDispose) {\n          this.#dispose?.(v as V, k as K, reason)\n        }\n        if (this.#hasDisposeAfter) {\n          this.#disposed?.push([v as V, k as K, reason])\n        }\n      }\n    }\n\n    this.#keyMap.clear()\n    this.#valList.fill(undefined)\n    this.#keyList.fill(undefined)\n    if (this.#ttls && this.#starts) {\n      this.#ttls.fill(0)\n      this.#starts.fill(0)\n      for (const t of this.#autopurgeTimers ?? []) {\n        if (t !== undefined) clearTimeout(t)\n      }\n      this.#autopurgeTimers?.fill(undefined)\n    }\n    if (this.#sizes) {\n      this.#sizes.fill(0)\n    }\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free.length = 0\n    this.#calculatedSize = 0\n    this.#size = 0\n    if (this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n  }\n}\n", "const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n  s: any\n): s is Minipass.Readable | Minipass.Writable =>\n  !!s &&\n  typeof s === 'object' &&\n  (s instanceof Minipass ||\n    s instanceof Stream ||\n    isReadable(s) ||\n    isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Readable).pipe === 'function' &&\n  // node core Writable streams have a pipe() method, but it throws\n  (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Writable).write === 'function' &&\n  typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n  ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n  b instanceof ArrayBuffer ||\n  (!!b &&\n    typeof b === 'object' &&\n    b.constructor &&\n    b.constructor.name === 'ArrayBuffer' &&\n    b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n  !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n  /**\n   * end the destination stream when the source stream ends\n   */\n  end?: boolean\n  /**\n   * proxy errors from the source stream to the destination stream\n   */\n  proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n  src: Minipass\n  dest: Minipass\n  opts: PipeOptions\n  ondrain: () => any\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    this.src = src\n    this.dest = dest as Minipass\n    this.opts = opts\n    this.ondrain = () => src[RESUME]()\n    this.dest.on('drain', this.ondrain)\n  }\n  unpipe() {\n    this.dest.removeListener('drain', this.ondrain)\n  }\n  // only here for the prototype\n  /* c8 ignore start */\n  proxyErrors(_er: any) {}\n  /* c8 ignore stop */\n  end() {\n    this.unpipe()\n    if (this.opts.end) this.dest.end()\n  }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n  unpipe() {\n    this.src.removeListener('error', this.proxyErrors)\n    super.unpipe()\n  }\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    super(src, dest, opts)\n    this.proxyErrors = (er: Error) => this.dest.emit('error', er)\n    src.on('error', this.proxyErrors)\n  }\n}\n\nexport namespace Minipass {\n  /**\n   * Encoding used to create a stream that outputs strings rather than\n   * Buffer objects.\n   */\n  export type Encoding = BufferEncoding | 'buffer' | null\n\n  /**\n   * Any stream that Minipass can pipe into\n   */\n  export type Writable =\n    | Minipass\n    | NodeJS.WriteStream\n    | (NodeJS.WriteStream & { fd: number })\n    | (EventEmitter & {\n        end(): any\n        write(chunk: any, ...args: any[]): any\n      })\n\n  /**\n   * Any stream that can be read from\n   */\n  export type Readable =\n    | Minipass\n    | NodeJS.ReadStream\n    | (NodeJS.ReadStream & { fd: number })\n    | (EventEmitter & {\n        pause(): any\n        resume(): any\n        pipe(...destArgs: any[]): any\n      })\n\n  /**\n   * Utility type that can be iterated sync or async\n   */\n  export type DualIterable = Iterable & AsyncIterable\n\n  type EventArguments = Record\n\n  /**\n   * The listing of events that a Minipass class can emit.\n   * Extend this when extending the Minipass class, and pass as\n   * the third template argument.  The key is the name of the event,\n   * and the value is the argument list.\n   *\n   * Any undeclared events will still be allowed, but the handler will get\n   * arguments as `unknown[]`.\n   */\n  export interface Events\n    extends EventArguments {\n    readable: []\n    data: [chunk: RType]\n    error: [er: unknown]\n    abort: [reason: unknown]\n    drain: []\n    resume: []\n    end: []\n    finish: []\n    prefinish: []\n    close: []\n    [DESTROYED]: [er?: unknown]\n    [ERROR]: [er: unknown]\n  }\n\n  /**\n   * String or buffer-like data that can be joined and sliced\n   */\n  export type ContiguousData =\n    | Buffer\n    | ArrayBufferLike\n    | ArrayBufferView\n    | string\n  export type BufferOrString = Buffer | string\n\n  /**\n   * Options passed to the Minipass constructor.\n   */\n  export type SharedOptions = {\n    /**\n     * Defer all data emission and other events until the end of the\n     * current tick, similar to Node core streams\n     */\n    async?: boolean\n    /**\n     * A signal which will abort the stream\n     */\n    signal?: AbortSignal\n    /**\n     * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n     * emit Buffer objects rather than strings.\n     *\n     * Conflicts with `objectMode`\n     */\n    encoding?: BufferEncoding | null | 'buffer'\n    /**\n     * Output data exactly as it was written, supporting non-buffer/string\n     * data (such as arbitrary objects, falsey values, etc.)\n     *\n     * Conflicts with `encoding`\n     */\n    objectMode?: boolean\n  }\n\n  /**\n   * Options for a string encoded output\n   */\n  export type EncodingOptions = SharedOptions & {\n    encoding: BufferEncoding\n    objectMode?: false\n  }\n\n  /**\n   * Options for contiguous data buffer output\n   */\n  export type BufferOptions = SharedOptions & {\n    encoding?: null | 'buffer'\n    objectMode?: false\n  }\n\n  /**\n   * Options for objectMode arbitrary output\n   */\n  export type ObjectModeOptions = SharedOptions & {\n    objectMode: true\n    encoding?: null\n  }\n\n  /**\n   * Utility type to determine allowed options based on read type\n   */\n  export type Options =\n    | ObjectModeOptions\n    | (T extends string\n        ? EncodingOptions\n        : T extends Buffer\n        ? BufferOptions\n        : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n  !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n    RType extends unknown = Buffer,\n    WType extends unknown = RType extends Minipass.BufferOrString\n      ? Minipass.ContiguousData\n      : RType,\n    Events extends Minipass.Events = Minipass.Events\n  >\n  extends EventEmitter\n  implements Minipass.DualIterable\n{\n  [FLOWING]: boolean = false;\n  [PAUSED]: boolean = false;\n  [PIPES]: Pipe[] = [];\n  [BUFFER]: RType[] = [];\n  [OBJECTMODE]: boolean;\n  [ENCODING]: BufferEncoding | null;\n  [ASYNC]: boolean;\n  [DECODER]: SD | null;\n  [EOF]: boolean = false;\n  [EMITTED_END]: boolean = false;\n  [EMITTING_END]: boolean = false;\n  [CLOSED]: boolean = false;\n  [EMITTED_ERROR]: unknown = null;\n  [BUFFERLENGTH]: number = 0;\n  [DESTROYED]: boolean = false;\n  [SIGNAL]?: AbortSignal;\n  [ABORTED]: boolean = false;\n  [DATALISTENERS]: number = 0;\n  [DISCARDED]: boolean = false\n\n  /**\n   * true if the stream can be written\n   */\n  writable: boolean = true\n  /**\n   * true if the stream can be read\n   */\n  readable: boolean = true\n\n  /**\n   * If `RType` is Buffer, then options do not need to be provided.\n   * Otherwise, an options object must be provided to specify either\n   * {@link Minipass.SharedOptions.objectMode} or\n   * {@link Minipass.SharedOptions.encoding}, as appropriate.\n   */\n  constructor(\n    ...args:\n      | [Minipass.ObjectModeOptions]\n      | (RType extends Buffer\n          ? [] | [Minipass.Options]\n          : [Minipass.Options])\n  ) {\n    const options: Minipass.Options = (args[0] ||\n      {}) as Minipass.Options\n    super()\n    if (options.objectMode && typeof options.encoding === 'string') {\n      throw new TypeError(\n        'Encoding and objectMode may not be used together'\n      )\n    }\n    if (isObjectModeOptions(options)) {\n      this[OBJECTMODE] = true\n      this[ENCODING] = null\n    } else if (isEncodingOptions(options)) {\n      this[ENCODING] = options.encoding\n      this[OBJECTMODE] = false\n    } else {\n      this[OBJECTMODE] = false\n      this[ENCODING] = null\n    }\n    this[ASYNC] = !!options.async\n    this[DECODER] = this[ENCODING]\n      ? (new StringDecoder(this[ENCODING]) as SD)\n      : null\n\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposeBuffer === true) {\n      Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n    }\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposePipes === true) {\n      Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n    }\n\n    const { signal } = options\n    if (signal) {\n      this[SIGNAL] = signal\n      if (signal.aborted) {\n        this[ABORT]()\n      } else {\n        signal.addEventListener('abort', () => this[ABORT]())\n      }\n    }\n  }\n\n  /**\n   * The amount of data stored in the buffer waiting to be read.\n   *\n   * For Buffer strings, this will be the total byte length.\n   * For string encoding streams, this will be the string character length,\n   * according to JavaScript's `string.length` logic.\n   * For objectMode streams, this is a count of the items waiting to be\n   * emitted.\n   */\n  get bufferLength() {\n    return this[BUFFERLENGTH]\n  }\n\n  /**\n   * The `BufferEncoding` currently in use, or `null`\n   */\n  get encoding() {\n    return this[ENCODING]\n  }\n\n  /**\n   * @deprecated - This is a read only property\n   */\n  set encoding(_enc) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * @deprecated - Encoding may only be set at instantiation time\n   */\n  setEncoding(_enc: Minipass.Encoding) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * True if this is an objectMode stream\n   */\n  get objectMode() {\n    return this[OBJECTMODE]\n  }\n\n  /**\n   * @deprecated - This is a read-only property\n   */\n  set objectMode(_om) {\n    throw new Error('objectMode must be set at instantiation time')\n  }\n\n  /**\n   * true if this is an async stream\n   */\n  get ['async'](): boolean {\n    return this[ASYNC]\n  }\n  /**\n   * Set to true to make this stream async.\n   *\n   * Once set, it cannot be unset, as this would potentially cause incorrect\n   * behavior.  Ie, a sync stream can be made async, but an async stream\n   * cannot be safely made sync.\n   */\n  set ['async'](a: boolean) {\n    this[ASYNC] = this[ASYNC] || !!a\n  }\n\n  // drop everything and get out of the flow completely\n  [ABORT]() {\n    this[ABORTED] = true\n    this.emit('abort', this[SIGNAL]?.reason)\n    this.destroy(this[SIGNAL]?.reason)\n  }\n\n  /**\n   * True if the stream has been aborted.\n   */\n  get aborted() {\n    return this[ABORTED]\n  }\n  /**\n   * No-op setter. Stream aborted status is set via the AbortSignal provided\n   * in the constructor options.\n   */\n  set aborted(_) {}\n\n  /**\n   * Write data into the stream\n   *\n   * If the chunk written is a string, and encoding is not specified, then\n   * `utf8` will be assumed. If the stream encoding matches the encoding of\n   * a written string, and the state of the string decoder allows it, then\n   * the string will be passed through to either the output or the internal\n   * buffer without any processing. Otherwise, it will be turned into a\n   * Buffer object for processing into the desired encoding.\n   *\n   * If provided, `cb` function is called immediately before return for\n   * sync streams, or on next tick for async streams, because for this\n   * base class, a chunk is considered \"processed\" once it is accepted\n   * and either emitted or buffered. That is, the callback does not indicate\n   * that the chunk has been eventually emitted, though of course child\n   * classes can override this function to do whatever processing is required\n   * and call `super.write(...)` only once processing is completed.\n   */\n  write(chunk: WType, cb?: () => void): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding,\n    cb?: () => void\n  ): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): boolean {\n    if (this[ABORTED]) return false\n    if (this[EOF]) throw new Error('write after end')\n\n    if (this[DESTROYED]) {\n      this.emit(\n        'error',\n        Object.assign(\n          new Error('Cannot call write after a stream was destroyed'),\n          { code: 'ERR_STREAM_DESTROYED' }\n        )\n      )\n      return true\n    }\n\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n\n    if (!encoding) encoding = 'utf8'\n\n    const fn = this[ASYNC] ? defer : nodefer\n\n    // convert array buffers and typed array views into buffers\n    // at some point in the future, we may want to do the opposite!\n    // leave strings and buffers as-is\n    // anything is only allowed if in object mode, so throw\n    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n      if (isArrayBufferView(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(\n          chunk.buffer,\n          chunk.byteOffset,\n          chunk.byteLength\n        )\n      } else if (isArrayBufferLike(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(chunk)\n      } else if (typeof chunk !== 'string') {\n        throw new Error(\n          'Non-contiguous data written to non-objectMode stream'\n        )\n      }\n    }\n\n    // handle object mode up front, since it's simpler\n    // this yields better performance, fewer checks later.\n    if (this[OBJECTMODE]) {\n      // maybe impossible?\n      /* c8 ignore start */\n      if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n      /* c8 ignore stop */\n\n      if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n      else this[BUFFERPUSH](chunk as unknown as RType)\n\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n      if (cb) fn(cb)\n\n      return this[FLOWING]\n    }\n\n    // at this point the chunk is a buffer or string\n    // don't buffer it up or send it to the decoder\n    if (!(chunk as Minipass.BufferOrString).length) {\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n      if (cb) fn(cb)\n      return this[FLOWING]\n    }\n\n    // fast-path writing strings of same encoding to a stream with\n    // an empty buffer, skipping the buffer/decoder dance\n    if (\n      typeof chunk === 'string' &&\n      // unless it is a string already ready for us to use\n      !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n    ) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = Buffer.from(chunk, encoding)\n    }\n\n    if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = this[DECODER].write(chunk)\n    }\n\n    // Note: flushing CAN potentially switch us into not-flowing mode\n    if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n    if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n    else this[BUFFERPUSH](chunk as unknown as RType)\n\n    if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n    if (cb) fn(cb)\n\n    return this[FLOWING]\n  }\n\n  /**\n   * Low-level explicit read method.\n   *\n   * In objectMode, the argument is ignored, and one item is returned if\n   * available.\n   *\n   * `n` is the number of bytes (or in the case of encoding streams,\n   * characters) to consume. If `n` is not provided, then the entire buffer\n   * is returned, or `null` is returned if no data is available.\n   *\n   * If `n` is greater that the amount of data in the internal buffer,\n   * then `null` is returned.\n   */\n  read(n?: number | null): RType | null {\n    if (this[DESTROYED]) return null\n    this[DISCARDED] = false\n\n    if (\n      this[BUFFERLENGTH] === 0 ||\n      n === 0 ||\n      (n && n > this[BUFFERLENGTH])\n    ) {\n      this[MAYBE_EMIT_END]()\n      return null\n    }\n\n    if (this[OBJECTMODE]) n = null\n\n    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n      // not object mode, so if we have an encoding, then RType is string\n      // otherwise, must be Buffer\n      this[BUFFER] = [\n        (this[ENCODING]\n          ? this[BUFFER].join('')\n          : Buffer.concat(\n              this[BUFFER] as Buffer[],\n              this[BUFFERLENGTH]\n            )) as RType,\n      ]\n    }\n\n    const ret = this[READ](n || null, this[BUFFER][0] as RType)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [READ](n: number | null, chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n    else {\n      const c = chunk as Minipass.BufferOrString\n      if (n === c.length || n === null) this[BUFFERSHIFT]()\n      else if (typeof c === 'string') {\n        this[BUFFER][0] = c.slice(n) as RType\n        chunk = c.slice(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      } else {\n        this[BUFFER][0] = c.subarray(n) as RType\n        chunk = c.subarray(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      }\n    }\n\n    this.emit('data', chunk)\n\n    if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n    return chunk\n  }\n\n  /**\n   * End the stream, optionally providing a final write.\n   *\n   * See {@link Minipass#write} for argument descriptions\n   */\n  end(cb?: () => void): this\n  end(chunk: WType, cb?: () => void): this\n  end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n  end(\n    chunk?: WType | (() => void),\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): this {\n    if (typeof chunk === 'function') {\n      cb = chunk as () => void\n      chunk = undefined\n    }\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n    if (chunk !== undefined) this.write(chunk, encoding)\n    if (cb) this.once('end', cb)\n    this[EOF] = true\n    this.writable = false\n\n    // if we haven't written anything, then go ahead and emit,\n    // even if we're not reading.\n    // we'll re-emit if a new 'end' listener is added anyway.\n    // This makes MP more suitable to write-only use cases.\n    if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n    return this\n  }\n\n  // don't let the internal resume be overwritten\n  [RESUME]() {\n    if (this[DESTROYED]) return\n\n    if (!this[DATALISTENERS] && !this[PIPES].length) {\n      this[DISCARDED] = true\n    }\n    this[PAUSED] = false\n    this[FLOWING] = true\n    this.emit('resume')\n    if (this[BUFFER].length) this[FLUSH]()\n    else if (this[EOF]) this[MAYBE_EMIT_END]()\n    else this.emit('drain')\n  }\n\n  /**\n   * Resume the stream if it is currently in a paused state\n   *\n   * If called when there are no pipe destinations or `data` event listeners,\n   * this will place the stream in a \"discarded\" state, where all data will\n   * be thrown away. The discarded state is removed if a pipe destination or\n   * data handler is added, if pause() is called, or if any synchronous or\n   * asynchronous iteration is started.\n   */\n  resume() {\n    return this[RESUME]()\n  }\n\n  /**\n   * Pause the stream\n   */\n  pause() {\n    this[FLOWING] = false\n    this[PAUSED] = true\n    this[DISCARDED] = false\n  }\n\n  /**\n   * true if the stream has been forcibly destroyed\n   */\n  get destroyed() {\n    return this[DESTROYED]\n  }\n\n  /**\n   * true if the stream is currently in a flowing state, meaning that\n   * any writes will be immediately emitted.\n   */\n  get flowing() {\n    return this[FLOWING]\n  }\n\n  /**\n   * true if the stream is currently in a paused state\n   */\n  get paused() {\n    return this[PAUSED]\n  }\n\n  [BUFFERPUSH](chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n    else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n    this[BUFFER].push(chunk)\n  }\n\n  [BUFFERSHIFT](): RType {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n    else\n      this[BUFFERLENGTH] -= (\n        this[BUFFER][0] as Minipass.BufferOrString\n      ).length\n    return this[BUFFER].shift() as RType\n  }\n\n  [FLUSH](noDrain: boolean = false) {\n    do {} while (\n      this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n      this[BUFFER].length\n    )\n\n    if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n  }\n\n  [FLUSHCHUNK](chunk: RType) {\n    this.emit('data', chunk)\n    return this[FLOWING]\n  }\n\n  /**\n   * Pipe all data emitted by this stream into the destination provided.\n   *\n   * Triggers the flow of data.\n   */\n  pipe(dest: W, opts?: PipeOptions): W {\n    if (this[DESTROYED]) return dest\n    this[DISCARDED] = false\n\n    const ended = this[EMITTED_END]\n    opts = opts || {}\n    if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n    else opts.end = opts.end !== false\n    opts.proxyErrors = !!opts.proxyErrors\n\n    // piping an ended stream ends immediately\n    if (ended) {\n      if (opts.end) dest.end()\n    } else {\n      // \"as\" here just ignores the WType, which pipes don't care about,\n      // since they're only consuming from us, and writing to the dest\n      this[PIPES].push(\n        !opts.proxyErrors\n          ? new Pipe(this as Minipass, dest, opts)\n          : new PipeProxyErrors(this as Minipass, dest, opts)\n      )\n      if (this[ASYNC]) defer(() => this[RESUME]())\n      else this[RESUME]()\n    }\n\n    return dest\n  }\n\n  /**\n   * Fully unhook a piped destination stream.\n   *\n   * If the destination stream was the only consumer of this stream (ie,\n   * there are no other piped destinations or `'data'` event listeners)\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  unpipe(dest: W) {\n    const p = this[PIPES].find(p => p.dest === dest)\n    if (p) {\n      if (this[PIPES].length === 1) {\n        if (this[FLOWING] && this[DATALISTENERS] === 0) {\n          this[FLOWING] = false\n        }\n        this[PIPES] = []\n      } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n      p.unpipe()\n    }\n  }\n\n  /**\n   * Alias for {@link Minipass#on}\n   */\n  addListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    return this.on(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.on`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * - Adding a 'data' event handler will trigger the flow of data\n   *\n   * - Adding a 'readable' event handler when there is data waiting to be read\n   *   will cause 'readable' to be emitted immediately.\n   *\n   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n   *   already passed will cause the event to be emitted immediately and all\n   *   handlers removed.\n   *\n   * - Adding an 'error' event handler after an error has been emitted will\n   *   cause the event to be re-emitted immediately with the error previously\n   *   raised.\n   */\n  on(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    const ret = super.on(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    if (ev === 'data') {\n      this[DISCARDED] = false\n      this[DATALISTENERS]++\n      if (!this[PIPES].length && !this[FLOWING]) {\n        this[RESUME]()\n      }\n    } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n      super.emit('readable')\n    } else if (isEndish(ev) && this[EMITTED_END]) {\n      super.emit(ev)\n      this.removeAllListeners(ev)\n    } else if (ev === 'error' && this[EMITTED_ERROR]) {\n      const h = handler as (...a: Events['error']) => any\n      if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n      else h.call(this, this[EMITTED_ERROR])\n    }\n    return ret\n  }\n\n  /**\n   * Alias for {@link Minipass#off}\n   */\n  removeListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    return this.off(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.off`\n   *\n   * If a 'data' event handler is removed, and it was the last consumer\n   * (ie, there are no pipe destinations or other 'data' event listeners),\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  off(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    const ret = super.off(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    // if we previously had listeners, and now we don't, and we don't\n    // have any pipes, then stop the flow, unless it's been explicitly\n    // put in a discarded flowing state via stream.resume().\n    if (ev === 'data') {\n      this[DATALISTENERS] = this.listeners('data').length\n      if (\n        this[DATALISTENERS] === 0 &&\n        !this[DISCARDED] &&\n        !this[PIPES].length\n      ) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.removeAllListeners`\n   *\n   * If all 'data' event handlers are removed, and they were the last consumer\n   * (ie, there are no pipe destinations), then the flow of data will stop\n   * until there is another consumer or {@link Minipass#resume} is explicitly\n   * called.\n   */\n  removeAllListeners(ev?: Event) {\n    const ret = super.removeAllListeners(ev as string | symbol | undefined)\n    if (ev === 'data' || ev === undefined) {\n      this[DATALISTENERS] = 0\n      if (!this[DISCARDED] && !this[PIPES].length) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * true if the 'end' event has been emitted\n   */\n  get emittedEnd() {\n    return this[EMITTED_END]\n  }\n\n  [MAYBE_EMIT_END]() {\n    if (\n      !this[EMITTING_END] &&\n      !this[EMITTED_END] &&\n      !this[DESTROYED] &&\n      this[BUFFER].length === 0 &&\n      this[EOF]\n    ) {\n      this[EMITTING_END] = true\n      this.emit('end')\n      this.emit('prefinish')\n      this.emit('finish')\n      if (this[CLOSED]) this.emit('close')\n      this[EMITTING_END] = false\n    }\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.emit`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * If the stream has been destroyed, and the event is something other\n   * than 'close' or 'error', then `false` is returned and no handlers\n   * are called.\n   *\n   * If the event is 'end', and has already been emitted, then the event\n   * is ignored. If the stream is in a paused or non-flowing state, then\n   * the event will be deferred until data flow resumes. If the stream is\n   * async, then handlers will be called on the next tick rather than\n   * immediately.\n   *\n   * If the event is 'close', and 'end' has not yet been emitted, then\n   * the event will be deferred until after 'end' is emitted.\n   *\n   * If the event is 'error', and an AbortSignal was provided for the stream,\n   * and there are no listeners, then the event is ignored, matching the\n   * behavior of node core streams in the presense of an AbortSignal.\n   *\n   * If the event is 'finish' or 'prefinish', then all listeners will be\n   * removed after emitting the event, to prevent double-firing.\n   */\n  emit(\n    ev: Event,\n    ...args: Events[Event]\n  ): boolean {\n    const data = args[0]\n    // error and close are only events allowed after calling destroy()\n    if (\n      ev !== 'error' &&\n      ev !== 'close' &&\n      ev !== DESTROYED &&\n      this[DESTROYED]\n    ) {\n      return false\n    } else if (ev === 'data') {\n      return !this[OBJECTMODE] && !data\n        ? false\n        : this[ASYNC]\n        ? (defer(() => this[EMITDATA](data as RType)), true)\n        : this[EMITDATA](data as RType)\n    } else if (ev === 'end') {\n      return this[EMITEND]()\n    } else if (ev === 'close') {\n      this[CLOSED] = true\n      // don't emit close before 'end' and 'finish'\n      if (!this[EMITTED_END] && !this[DESTROYED]) return false\n      const ret = super.emit('close')\n      this.removeAllListeners('close')\n      return ret\n    } else if (ev === 'error') {\n      this[EMITTED_ERROR] = data\n      super.emit(ERROR, data)\n      const ret =\n        !this[SIGNAL] || this.listeners('error').length\n          ? super.emit('error', data)\n          : false\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'resume') {\n      const ret = super.emit('resume')\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'finish' || ev === 'prefinish') {\n      const ret = super.emit(ev)\n      this.removeAllListeners(ev)\n      return ret\n    }\n\n    // Some other unknown event\n    const ret = super.emit(ev as string, ...args)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITDATA](data: RType) {\n    for (const p of this[PIPES]) {\n      if (p.dest.write(data as RType) === false) this.pause()\n    }\n    const ret = this[DISCARDED] ? false : super.emit('data', data)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITEND]() {\n    if (this[EMITTED_END]) return false\n\n    this[EMITTED_END] = true\n    this.readable = false\n    return this[ASYNC]\n      ? (defer(() => this[EMITEND2]()), true)\n      : this[EMITEND2]()\n  }\n\n  [EMITEND2]() {\n    if (this[DECODER]) {\n      const data = this[DECODER].end()\n      if (data) {\n        for (const p of this[PIPES]) {\n          p.dest.write(data as RType)\n        }\n        if (!this[DISCARDED]) super.emit('data', data)\n      }\n    }\n\n    for (const p of this[PIPES]) {\n      p.end()\n    }\n    const ret = super.emit('end')\n    this.removeAllListeners('end')\n    return ret\n  }\n\n  /**\n   * Return a Promise that resolves to an array of all emitted data once\n   * the stream ends.\n   */\n  async collect(): Promise {\n    const buf: RType[] & { dataLength: number } = Object.assign([], {\n      dataLength: 0,\n    })\n    if (!this[OBJECTMODE]) buf.dataLength = 0\n    // set the promise first, in case an error is raised\n    // by triggering the flow here.\n    const p = this.promise()\n    this.on('data', c => {\n      buf.push(c)\n      if (!this[OBJECTMODE])\n        buf.dataLength += (c as Minipass.BufferOrString).length\n    })\n    await p\n    return buf\n  }\n\n  /**\n   * Return a Promise that resolves to the concatenation of all emitted data\n   * once the stream ends.\n   *\n   * Not allowed on objectMode streams.\n   */\n  async concat(): Promise {\n    if (this[OBJECTMODE]) {\n      throw new Error('cannot concat in objectMode')\n    }\n    const buf = await this.collect()\n    return (\n      this[ENCODING]\n        ? buf.join('')\n        : Buffer.concat(buf as Buffer[], buf.dataLength)\n    ) as RType\n  }\n\n  /**\n   * Return a void Promise that resolves once the stream ends.\n   */\n  async promise(): Promise {\n    return new Promise((resolve, reject) => {\n      this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n      this.on('error', er => reject(er))\n      this.on('end', () => resolve())\n    })\n  }\n\n  /**\n   * Asynchronous `for await of` iteration.\n   *\n   * This will continue emitting all chunks until the stream terminates.\n   */\n  [Symbol.asyncIterator](): AsyncGenerator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = async (): Promise> => {\n      this.pause()\n      stopped = true\n      return { value: undefined, done: true }\n    }\n    const next = (): Promise> => {\n      if (stopped) return stop()\n      const res = this.read()\n      if (res !== null) return Promise.resolve({ done: false, value: res })\n\n      if (this[EOF]) return stop()\n\n      let resolve!: (res: IteratorResult) => void\n      let reject!: (er: unknown) => void\n      const onerr = (er: unknown) => {\n        this.off('data', ondata)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        reject(er)\n      }\n      const ondata = (value: RType) => {\n        this.off('error', onerr)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        this.pause()\n        resolve({ value, done: !!this[EOF] })\n      }\n      const onend = () => {\n        this.off('error', onerr)\n        this.off('data', ondata)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        resolve({ done: true, value: undefined })\n      }\n      const ondestroy = () => onerr(new Error('stream destroyed'))\n      return new Promise>((res, rej) => {\n        reject = rej\n        resolve = res\n        this.once(DESTROYED, ondestroy)\n        this.once('error', onerr)\n        this.once('end', onend)\n        this.once('data', ondata)\n      })\n    }\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.asyncIterator]() {\n        return this\n      },\n      [Symbol.asyncDispose]: async () => {},\n    }\n  }\n\n  /**\n   * Synchronous `for of` iteration.\n   *\n   * The iteration will terminate when the internal buffer runs out, even\n   * if the stream has not yet terminated.\n   */\n  [Symbol.iterator](): Generator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = (): IteratorReturnResult => {\n      this.pause()\n      this.off(ERROR, stop)\n      this.off(DESTROYED, stop)\n      this.off('end', stop)\n      stopped = true\n      return { done: true, value: undefined }\n    }\n\n    const next = (): IteratorResult => {\n      if (stopped) return stop()\n      const value = this.read()\n      return value === null ? stop() : { done: false, value }\n    }\n\n    this.once('end', stop)\n    this.once(ERROR, stop)\n    this.once(DESTROYED, stop)\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.iterator]() {\n        return this\n      },\n      [Symbol.dispose]: () => {},\n    }\n  }\n\n  /**\n   * Destroy a stream, preventing it from being used for any further purpose.\n   *\n   * If the stream has a `close()` method, then it will be called on\n   * destruction.\n   *\n   * After destruction, any attempt to write data, read data, or emit most\n   * events will be ignored.\n   *\n   * If an error argument is provided, then it will be emitted in an\n   * 'error' event.\n   */\n  destroy(er?: unknown) {\n    if (this[DESTROYED]) {\n      if (er) this.emit('error', er)\n      else this.emit(DESTROYED)\n      return this\n    }\n\n    this[DESTROYED] = true\n    this[DISCARDED] = true\n\n    // throw away all buffered data, it's never coming out\n    this[BUFFER].length = 0\n    this[BUFFERLENGTH] = 0\n\n    const wc = this as Minipass & {\n      close?: () => void\n    }\n    if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n    if (er) this.emit('error', er)\n    // if no error to emit, still reject pending promises\n    else this.emit(DESTROYED)\n\n    return this\n  }\n\n  /**\n   * Alias for {@link isStream}\n   *\n   * Former export location, maintained for backwards compatibility.\n   *\n   * @deprecated\n   */\n  static get isStream() {\n    return isStream\n  }\n}\n", "import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises || {}),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n  rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new LRUCache({ max: 2 ** 12 })\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new LRUCache({ max: 2 ** 12 })\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /* c8 ignore start */\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   *\n   * @deprecated\n   */\n  get path(): string {\n    return this.parentPath\n  }\n  /* c8 ignore stop */\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    if (rootPath === this.root.name) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(\n      rootPath,\n      this,\n    ).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    rootPath = rootPath\n      .toUpperCase()\n      .replace(/\\//g, '\\\\')\n      .replace(uncDriveRegexp, '$1\\\\')\n    return rootPath === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n", "// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\nconst customInspect = Symbol.for('nodejs.util.inspect.custom')\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  [customInspect]() {\n    return 'Pattern <' + this.#globList.slice(this.#index).join('/') + '>'\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n", "// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      platform = defaultPlatform,\n    }: GlobWalkerOpts,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    this.mmopts = {\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n    }\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const m = new Minimatch(p.globString(), this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = p.fullpath() + '/'\n    const relative = (p.relative() || '.') + '/'\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n", "// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n", "/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Set\n  : O extends GWOFileTypesFalse ? Set\n  : O extends GWOFileTypesUnset ? Set\n  : Set\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts)\n  : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n          '.' + this.#sep\n        : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  matches = new Set>()\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise>> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Set> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n", "import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n  FSOption,\n  Path,\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be eiher a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignored` and `childrenIgnored`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  ignore?: string | string[] | IgnoreLike\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Just passed along to Minimatch.  Note that this makes all pattern\n   * matching operations slower and *extremely* noisy.\n   */\n  debug?: boolean\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n\n  /**\n   * max number of `{...}` patterns to expand. Default `1_000`.\n   *\n   * Note: this is much less than minimatch's default of `100_000`,\n   * because Glob has higher memory requirements due to walking\n   * the file system tree.\n   */\n  braceExpandMax?: number\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[]\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    if (typeof pattern === 'string') {\n      pattern = [pattern]\n    }\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = pattern\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      braceExpandMax: 10_000,\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      // default nocase based on platform\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n      debug: !!this.opts.debug,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return [\n      ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walk()),\n    ]\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return [\n      ...new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walkSync(),\n    ]\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n", "import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  if (!Array.isArray(pattern)) {\n    pattern = [pattern]\n  }\n  for (const p of pattern) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n", "import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n"],
-  "mappings": "gLAAO,IAAMA,GAAW,CACtBC,EACAC,EACAC,IACE,CACF,IAAMC,EAAKH,aAAa,OAASI,GAAWJ,EAAGE,CAAG,EAAIF,EAChDK,EAAKJ,aAAa,OAASG,GAAWH,EAAGC,CAAG,EAAID,EAEhD,EAAIE,IAAO,MAAQE,GAAM,SAAQC,EAAA,OAAMH,EAAIE,EAAIH,CAAG,EAExD,OACE,GAAK,CACH,MAAO,EAAE,CAAC,EACV,IAAK,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AAKM,EAASC,CAAO,EAAE,WAAU,CAC9C,CAsBA,SAAgBZ,GACdW,EACAC,EAAuB,CAAA,EAAE,CAEzB,OAAO,IAAIP,GAAA,KAAKM,EAASC,CAAO,EAAE,OAAM,CAC1C,CAqBA,SAAgBX,GACdU,EACAC,EAAuB,CAAA,EAAE,CAEzB,OAAO,IAAIP,GAAA,KAAKM,EAASC,CAAO,EAAE,SAAQ,CAC5C,CAwBA,eAAeC,GACbF,EACAC,EAAuB,CAAA,EAAE,CAEzB,OAAO,IAAIP,GAAA,KAAKM,EAASC,CAAO,EAAE,KAAI,CACxC,CAqBA,SAAgBV,GACdS,EACAC,EAAuB,CAAA,EAAE,CAEzB,OAAO,IAAIP,GAAA,KAAKM,EAASC,CAAO,EAAE,YAAW,CAC/C,CAqBA,SAAgBT,GACdQ,EACAC,EAAuB,CAAA,EAAE,CAEzB,OAAO,IAAIP,GAAA,KAAKM,EAASC,CAAO,EAAE,QAAO,CAC3C,CAGa,QAAA,WAAab,GACb,QAAA,OAAS,OAAO,OAAOC,GAAY,CAAE,KAAMD,EAAc,CAAE,EAC3D,QAAA,YAAcG,GACd,QAAA,QAAU,OAAO,OAAOC,GAAa,CAChD,KAAMD,GACP,EACY,QAAA,KAAO,OAAO,OAAOD,GAAU,CAC1C,OAAQF,GACR,QAASG,GACV,EAEY,QAAA,KAAO,OAAO,OAAOW,GAAO,CACvC,KAAMA,GACN,SAAAZ,GACA,KAAA,QAAA,KACA,WAAAD,GACA,OAAA,QAAA,OACA,eAAAD,GACA,WAAA,QAAA,WACA,YAAAI,GACA,QAAA,QAAA,QACA,gBAAAD,GACA,YAAA,QAAA,YACA,KAAAG,GAAA,KACA,SAAAC,GAAA,SACA,OAAAF,GAAA,OACA,SAAAA,GAAA,SACD,EACD,QAAA,KAAK,KAAO,QAAA",
-  "names": ["balanced", "a", "b", "str", "ma", "maybeMatch", "mb", "exports", "reg", "m", "range", "begs", "beg", "left", "right", "result", "ai", "bi", "i", "r", "exports", "expand", "balanced_match_1", "escSlash", "escOpen", "escClose", "escComma", "escPeriod", "escSlashPattern", "escOpenPattern", "escClosePattern", "escCommaPattern", "escPeriodPattern", "slashPattern", "openPattern", "closePattern", "commaPattern", "periodPattern", "numeric", "str", "escapeBraces", "unescapeBraces", "parseCommaParts", "parts", "m", "pre", "body", "post", "p", "postParts", "options", "max", "expand_", "embrace", "isPadded", "el", "lte", "i", "y", "gte", "isTop", "expansions", "k", "expansion", "isNumericSequence", "isAlphaSequence", "isSequence", "isOptions", "n", "N", "x", "width", "incr", "test", "pad", "c", "need", "z", "j", "MAX_PATTERN_LENGTH", "assertValidPattern", "pattern", "exports", "posixClasses", "braceEscape", "s", "regexpEscape", "rangesToString", "ranges", "parseClass", "glob", "position", "pos", "negs", "i", "sawStart", "uflag", "escaping", "negate", "endPos", "rangeStart", "WHILE", "c", "cls", "unip", "u", "neg", "r", "sranges", "snegs", "exports", "unescape", "s", "windowsPathsNoEscape", "magicalBraces", "exports", "brace_expressions_js_1", "unescape_js_1", "types", "isExtglobType", "c", "startNoTraversal", "startNoDot", "addPatternStart", "justDots", "reSpecials", "regExpEscape", "s", "qmark", "star", "starNoEmpty", "AST", "_AST", "#root", "#hasMagic", "#uflag", "#parts", "#parent", "#parentIndex", "#negs", "#filledNegs", "#options", "#toString", "#emptyExt", "type", "parent", "options", "p", "#fillNegs", "n", "pp", "part", "parts", "ret", "i", "pl", "#parseAST", "str", "ast", "pos", "opt", "escaping", "inBrace", "braceStart", "braceNeg", "acc", "ext", "pattern", "glob", "re", "body", "hasMagic", "uflag", "flags", "allowDot", "dot", "noEmpty", "src", "_", "#parseGlob", "start", "aps", "needNoTrav", "needNoDot", "end", "repeated", "#partsToRegExp", "bodyDotAllowed", "final", "close", "_hasMagic", "inStar", "needUflag", "consumed", "magic", "exports", "escape", "s", "windowsPathsNoEscape", "magicalBraces", "exports", "brace_expansion_1", "assert_valid_pattern_js_1", "ast_js_1", "escape_js_1", "unescape_js_1", "minimatch", "p", "pattern", "options", "Minimatch", "exports", "starDotExtRE", "starDotExtTest", "ext", "f", "starDotExtTestDot", "starDotExtTestNocase", "starDotExtTestNocaseDot", "starDotStarRE", "starDotStarTest", "starDotStarTestDot", "dotStarRE", "dotStarTest", "starRE", "starTest", "starTestDot", "qmarksRE", "qmarksTestNocase", "$0", "noext", "qmarksTestNoExt", "qmarksTestNocaseDot", "qmarksTestNoExtDot", "qmarksTestDot", "qmarksTest", "len", "defaultPlatform", "path", "qmark", "star", "twoStarDot", "twoStarNoDot", "filter", "a", "b", "defaults", "def", "orig", "type", "parent", "list", "braceExpand", "makeRe", "match", "mm", "globMagic", "regExpEscape", "s", "awe", "part", "_", "args", "rawGlobParts", "set", "__", "isUNC", "isDrive", "ss", "i", "globParts", "j", "optimizationLevel", "parts", "gs", "prev", "didSomething", "dd", "gss", "next", "p2", "other", "splin", "matched", "emptyGSMatch", "ai", "bi", "result", "which", "negate", "negateOffset", "file", "partial", "fileDrive", "fileUNC", "patternDrive", "patternUNC", "fdi", "pdi", "fd", "pd", "fi", "pi", "fl", "pl", "fr", "pr", "swallowee", "hit", "m", "fastTest", "re", "twoStar", "flags", "pp", "filtered", "prefixes", "open", "close", "ff", "filename", "ast_js_2", "escape_js_2", "unescape_js_2", "defaultPerf", "warned", "PROCESS", "emitWarning", "msg", "type", "code", "fn", "AC", "AS", "_", "warnACPolyfill", "reason", "printACPolyfillWarning", "shouldWarn", "isPosInt", "n", "getUintArray", "max", "ZeroArray", "size", "Stack", "_Stack", "#constructing", "HeapCls", "s", "LRUCache", "_LRUCache", "#max", "#maxSize", "#dispose", "#onInsert", "#disposeAfter", "#fetchMethod", "#memoMethod", "#perf", "#size", "#calculatedSize", "#keyMap", "#keyList", "#valList", "#next", "#prev", "#head", "#tail", "#free", "#disposed", "#sizes", "#starts", "#ttls", "#autopurgeTimers", "#hasDispose", "#hasFetchMethod", "#hasDisposeAfter", "#hasOnInsert", "c", "p", "#isBackgroundFetch", "k", "index", "options", "context", "#backgroundFetch", "#moveToTail", "#indexes", "#rindexes", "#isStale", "ttl", "ttlResolution", "ttlAutopurge", "updateAgeOnGet", "updateAgeOnHas", "allowStale", "dispose", "onInsert", "disposeAfter", "noDisposeOnSet", "noUpdateTTL", "maxSize", "maxEntrySize", "sizeCalculation", "fetchMethod", "memoMethod", "noDeleteOnFetchRejection", "noDeleteOnStaleGet", "allowStaleOnFetchRejection", "allowStaleOnFetchAbort", "ignoreFetchAbort", "perf", "UintArray", "#initializeSizeTracking", "#initializeTTLTracking", "key", "ttls", "starts", "purgeTimers", "#setItemTTL", "start", "t", "#delete", "#updateItemAge", "#statusTTL", "status", "cachedNow", "getNow", "age", "sizes", "#removeItemSize", "#requireSize", "v", "#addItemSize", "#evict", "_i", "_s", "_st", "_k", "_v", "i", "#isValidIndex", "getOptions", "value", "thisp", "deleted", "entry", "remain", "arr", "setOptions", "oldVal", "oldValue", "dt", "task", "val", "free", "head", "hasOptions", "peekOptions", "ac", "signal", "fetchOpts", "cb", "updateCache", "aborted", "ignoreAbort", "proceed", "fetchFail", "bf", "vl", "eb", "er", "allowStaleAborted", "noDelete", "pcall", "res", "rej", "fmp", "b", "fetchOptions", "forceRefresh", "stale", "isStale", "staleVal", "memoOptions", "vv", "fetching", "#connect", "#clear", "pi", "ni", "exports", "proc", "node_events_1", "node_stream_1", "__importDefault", "node_string_decoder_1", "isStream", "s", "Minipass", "exports", "isReadable", "isWritable", "EOF", "MAYBE_EMIT_END", "EMITTED_END", "EMITTING_END", "EMITTED_ERROR", "CLOSED", "READ", "FLUSH", "FLUSHCHUNK", "ENCODING", "DECODER", "FLOWING", "PAUSED", "RESUME", "BUFFER", "PIPES", "BUFFERLENGTH", "BUFFERPUSH", "BUFFERSHIFT", "OBJECTMODE", "DESTROYED", "ERROR", "EMITDATA", "EMITEND", "EMITEND2", "ASYNC", "ABORT", "ABORTED", "SIGNAL", "DATALISTENERS", "DISCARDED", "defer", "fn", "nodefer", "isEndish", "ev", "isArrayBufferLike", "b", "isArrayBufferView", "Pipe", "src", "dest", "opts", "_er", "PipeProxyErrors", "er", "isObjectModeOptions", "o", "isEncodingOptions", "args", "options", "signal", "_enc", "_om", "a", "_", "chunk", "encoding", "cb", "n", "ret", "c", "noDrain", "ended", "p", "handler", "h", "data", "buf", "resolve", "reject", "stopped", "stop", "res", "onerr", "ondata", "onend", "ondestroy", "value", "rej", "next", "wc", "lru_cache_1", "node_path_1", "node_url_1", "fs_1", "actualFS", "__importStar", "realpathSync", "promises_1", "minipass_1", "defaultFS", "fsFromOption", "fsOption", "uncDriveRegexp", "uncToDrive", "rootPath", "eitherSep", "UNKNOWN", "IFIFO", "IFCHR", "IFDIR", "IFBLK", "IFREG", "IFLNK", "IFSOCK", "IFMT", "IFMT_UNKNOWN", "READDIR_CALLED", "LSTAT_CALLED", "ENOTDIR", "ENOENT", "ENOREADLINK", "ENOREALPATH", "ENOCHILD", "TYPEMASK", "entToType", "s", "normalizeCache", "normalize", "c", "n", "normalizeNocaseCache", "normalizeNocase", "ResolveCache", "exports", "ChildrenCache", "maxSize", "a", "setAsCwd", "PathBase", "#fs", "#dev", "#mode", "#nlink", "#uid", "#gid", "#rdev", "#blksize", "#ino", "#size", "#blocks", "#atimeMs", "#mtimeMs", "#ctimeMs", "#birthtimeMs", "#atime", "#mtime", "#ctime", "#birthtime", "#matchName", "#depth", "#fullpath", "#fullpathPosix", "#relative", "#relativePosix", "#type", "#children", "#linkTarget", "#realpath", "name", "type", "root", "roots", "nocase", "children", "opts", "path", "dirParts", "#resolveParts", "p", "part", "cached", "pathPart", "fullpath", "pchild", "pv", "fp", "pfpp", "fpp", "ifmt", "target", "read", "linkTarget", "er", "#readlinkFail", "#readdirSuccess", "#markENOENT", "#markChildrenENOENT", "#markENOREALPATH", "#markENOTDIR", "#readdirFail", "code", "#lstatFail", "ter", "#readdirAddChild", "e", "#readdirMaybePromoteChild", "#readdirAddNewChild", "child", "#readdirPromoteChild", "index", "v", "#applyStat", "st", "atime", "atimeMs", "birthtime", "birthtimeMs", "blksize", "blocks", "ctime", "ctimeMs", "dev", "gid", "ino", "mode", "mtime", "mtimeMs", "nlink", "rdev", "size", "uid", "#onReaddirCB", "#readdirCBInFlight", "#callOnReaddirCB", "cbs", "cb", "allowZalgo", "entries", "#asyncReaddirInFlight", "resolve", "res", "dirs", "walkFilter", "rp", "oldCwd", "changed", "PathWin32", "_PathWin32", "compare", "PathScurryWin32", "PathPosix", "_PathPosix", "_rootPath", "PathScurryBase", "#resolveCache", "#resolvePosixCache", "cwd", "pathImpl", "sep", "childrenCacheSize", "fs", "cwdPath", "split", "prev", "len", "joinSep", "abs", "sawFirst", "l", "paths", "r", "i", "result", "entry", "withFileTypes", "follow", "filter", "results", "walk", "dir", "next", "start", "rej", "options", "queue", "processing", "process", "paused", "onReaddir", "didRealpaths", "promises", "sync", "PathScurryPosix", "_dir", "PathScurryDarwin", "minimatch_1", "isPatternList", "pl", "isGlobList", "gl", "customInspect", "Pattern", "_Pattern", "#patternList", "#globList", "#index", "#platform", "#rest", "#globString", "#isDrive", "#isUNC", "#isAbsolute", "#followGlobstar", "patternList", "globList", "index", "platform", "p0", "p1", "p2", "p3", "prest", "g0", "g1", "g2", "g3", "grest", "g", "p", "exports", "minimatch_1", "pattern_js_1", "defaultPlatform", "Ignore", "ignored", "nobrace", "nocase", "noext", "noglobstar", "platform", "ign", "mm", "i", "parsed", "globParts", "p", "m", "children", "absolute", "fullpath", "fullpaths", "relative", "relatives", "exports", "minimatch_1", "HasWalkedCache", "_HasWalkedCache", "store", "target", "pattern", "fullpath", "cached", "exports", "MatchRecord", "absolute", "ifDir", "n", "current", "path", "SubWalks", "subs", "p", "k", "Processor", "_Processor", "opts", "hasWalkedCache", "patterns", "processingSet", "t", "root", "rest", "changed", "rp", "rrest", "tp", "parent", "entries", "results", "e", "ep", "minipass_1", "ignore_js_1", "processor_js_1", "makeIgnore", "ignore", "opts", "GlobUtil", "#onResume", "#ignore", "#sep", "patterns", "path", "m", "#ignored", "#childrenIgnored", "fn", "e", "ifDir", "rpc", "s", "target", "absolute", "ign", "abs", "mark", "rel", "pre", "p", "cb", "processor", "tasks", "next", "t", "childrenCached", "_", "entries", "children", "exports", "GlobWalker", "res", "rej", "GlobStream", "minimatch_1", "node_url_1", "path_scurry_1", "pattern_js_1", "walker_js_1", "defaultPlatform", "Glob", "pattern", "opts", "p", "Scurry", "nocaseMagicOnly", "mmo", "mms", "matchSet", "globParts", "set", "m", "i", "g", "exports", "minimatch_1", "hasMagic", "pattern", "options", "p", "exports", "globStreamSync", "globStream", "globSync", "globIterateSync", "globIterate", "minimatch_1", "glob_js_1", "has_magic_js_1", "minimatch_2", "glob_js_2", "has_magic_js_2", "ignore_js_1", "pattern", "options", "glob_"]
+  "sources": ["../../node_modules/balanced-match/src/index.ts", "../../node_modules/brace-expansion/src/index.ts", "../../node_modules/@isaacs/nonrecursive-glob-match/src/numeric-range.ts", "../../node_modules/@isaacs/nonrecursive-glob-match/src/parse-class.ts", "../../node_modules/@isaacs/nonrecursive-glob-match/src/index.ts", "../../node_modules/minimatch/src/assert-valid-pattern.ts", "../../node_modules/minimatch/src/escape.ts", "../../node_modules/minimatch/src/unescape.ts", "../../node_modules/minimatch/src/index.ts", "../../node_modules/lru-cache/src/diagnostics-channel-node.ts", "../../node_modules/lru-cache/src/perf.ts", "../../node_modules/lru-cache/src/index.ts", "../../node_modules/minipass/src/index.ts", "../../node_modules/path-scurry/src/index.ts", "../../src/pattern.ts", "../../src/ignore.ts", "../../src/processor.ts", "../../src/walker.ts", "../../src/glob.ts", "../../src/has-magic.ts", "../../src/index.ts"],
+  "sourcesContent": ["export const balanced = (\n  a: string | RegExp,\n  b: string | RegExp,\n  str: string,\n) => {\n  const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n  const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n  const r = ma !== null && mb != null && range(ma, mb, str)\n\n  return (\n    r && {\n      start: r[0],\n      end: r[1],\n      pre: str.slice(0, r[0]),\n      body: str.slice(r[0] + ma.length, r[1]),\n      post: str.slice(r[1] + mb.length),\n    }\n  )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n  const m = str.match(reg)\n  return m ? m[0] : null\n}\n\nexport const range = (\n  a: string,\n  b: string,\n  str: string,\n): undefined | [number, number] => {\n  let begs: number[],\n    beg: number | undefined,\n    left: number,\n    right: number | undefined = undefined,\n    result: undefined | [number, number]\n  let ai = str.indexOf(a)\n  let bi = str.indexOf(b, ai + 1)\n  let i = ai\n\n  if (ai >= 0 && bi > 0) {\n    if (a === b) {\n      return [ai, bi]\n    }\n    begs = []\n    left = str.length\n\n    while (i >= 0 && !result) {\n      if (i === ai) {\n        begs.push(i)\n        ai = str.indexOf(a, i + 1)\n      } else if (begs.length === 1) {\n        const r = begs.pop()\n        if (r !== undefined) result = [r, bi]\n      } else {\n        beg = begs.pop()\n        if (beg !== undefined && beg < left) {\n          left = beg\n          right = bi\n        }\n\n        bi = str.indexOf(b, i + 1)\n      }\n\n      i = ai < bi && ai >= 0 ? ai : bi\n    }\n\n    if (begs.length && right !== undefined) {\n      result = [left, right]\n    }\n  }\n\n  return result\n}\n", "import { balanced } from 'balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\\\./g\n\nexport const EXPANSION_MAX = 100_000\n\n// `EXPANSION_MAX` caps the *number* of expansions, but not their length. An\n// input like `'{a,b}'.repeat(1500)` stays under that count - its output is\n// truncated to 100k results - while making every result ~1500 characters\n// long. The result set, and the intermediate arrays built while combining\n// brace sets, then grow large enough to exhaust memory and crash the process\n// (CVE-2026-14257). `EXPANSION_MAX_LENGTH` bounds the total number of\n// characters the accumulator may hold at any point, so memory stays flat no\n// matter how many brace groups are chained. The limit sits well above any\n// realistic expansion (100k results hitting `EXPANSION_MAX` measure ~1M\n// characters) so legitimate input is unaffected.\nexport const EXPANSION_MAX_LENGTH = 4_000_000\n\n// `expand_` recurses once per level of brace *nesting* - both when expanding a\n// set's comma members and when re-wrapping a set whose body is a single part.\n// The CVE-2026-14257 fix made the *tail* iterative (recursion on `m.post`, one\n// level per chained group), which left nesting depth unbounded: about 3,100\n// levels of `{{{...a,b...}}}` - only ~6KB of input - exhausted the native stack\n// and crashed the process. `EXPANSION_MAX_DEPTH` bounds how deep the parser\n// will follow nesting. It sits far above any realistic pattern and well below\n// the depth at which the stack runs out.\nexport const EXPANSION_MAX_DEPTH = 1_000\n\n// Bash keeps a quirk where a brace group followed by a comma set still expands\n// (`{a},b}`). The parser implements it by rewriting the string and restarting\n// the scan, absorbing one `}` per pass. `n` trailing braces therefore cost `n`\n// full passes over a string that itself grows by one `escClose` sentinel each\n// time - quadratic in `n`, with a ~26x constant from the sentinel's length.\n// 128KB of `'{a}' + '}'.repeat(n) + ',z}'` blocked the event loop for 27\n// seconds to produce two results. `EXPANSION_MAX_REWRITES` bounds how many\n// times the scan may restart. Real `{a},b}` input needs a handful.\nexport const EXPANSION_MAX_REWRITES = 1_000\n\nfunction numeric(str: string) {\n  return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n  return str\n    .replace(slashPattern, escSlash)\n    .replace(openPattern, escOpen)\n    .replace(closePattern, escClose)\n    .replace(commaPattern, escComma)\n    .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n  return str\n    .replace(escSlashPattern, '\\\\')\n    .replace(escOpenPattern, '{')\n    .replace(escClosePattern, '}')\n    .replace(escCommaPattern, ',')\n    .replace(escPeriodPattern, '.')\n}\n\n// Like `target.push(...items)` but doesn't overflow the stack\nfunction pushAll(target: string[], items: string[]) {\n  for (let i = 0; i < items.length; i++) {\n    target.push(items[i] as string)\n  }\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n  const parts: string[] = []\n\n  // Walk the brace groups iteratively. Recursing on `post` once per group let a\n  // chain of them exhaust the stack - the parsing-side counterpart to\n  // the `expand_` overflow fixed for CVE-2026-14257, and not something `max` or\n  // `maxLength` can bound, since it happens before expansion.\n  //\n  // The part the next chunk continues\n  let carry = ''\n\n  for (;;) {\n    const m = balanced('{', '}', str)\n\n    if (!m) {\n      const tail = str.split(',')\n      tail[0] = carry + (tail[0] as string)\n      pushAll(parts, tail)\n      return parts\n    }\n\n    const { pre, body, post } = m\n    const p = pre.split(',')\n    p[0] = carry + (p[0] as string)\n    p[p.length - 1] += '{' + body + '}'\n\n    if (!post.length) {\n      pushAll(parts, p)\n      return parts\n    }\n\n    carry = p.pop() as string\n    pushAll(parts, p)\n    str = post\n  }\n}\n\nexport type BraceExpansionOptions = {\n  max?: number\n  maxLength?: number\n  maxDepth?: number\n  maxRewrites?: number\n}\n\nexport function expand(str: string, options: BraceExpansionOptions = {}) {\n  if (!str) {\n    return []\n  }\n\n  const {\n    max = EXPANSION_MAX,\n    maxLength = EXPANSION_MAX_LENGTH,\n    maxDepth = EXPANSION_MAX_DEPTH,\n    maxRewrites = EXPANSION_MAX_REWRITES,\n  } = options\n\n  // I don't know why Bash 4.3 does this, but it does.\n  // Anything starting with {} will have the first two bytes preserved\n  // but *only* at the top level, so {},a}b will not expand to anything,\n  // but a{},b}c will be expanded to [a}c,abc].\n  // One could argue that this is a bug in Bash, but since the goal of\n  // this module is to match Bash's rules, we escape a leading {}\n  if (str.slice(0, 2) === '{}') {\n    str = '\\\\{\\\\}' + str.slice(2)\n  }\n\n  return expand_(\n    escapeBraces(str),\n    max,\n    maxLength,\n    maxDepth,\n    0,\n    maxRewrites,\n    true,\n  ).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n  return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n  return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n  return i <= y\n}\n\nfunction gte(i: number, y: number) {\n  return i >= y\n}\n\n// Build `{ acc[a] + pre + values[v] }` for every combination, capping the\n// number of results at `max` and the total number of characters at `maxLength`.\n// This is the one place output grows, so bounding it here keeps the single\n// accumulator - and therefore memory - flat regardless of how many brace groups\n// are combined (CVE-2026-14257).\nfunction combine(\n  acc: string[],\n  pre: string,\n  values: string[],\n  max: number,\n  maxLength: number,\n  dropEmpties: boolean,\n): string[] {\n  const out: string[] = []\n  let length = 0\n  for (let a = 0; a < acc.length; a++) {\n    for (let v = 0; v < values.length; v++) {\n      if (out.length >= max) return out\n      const expansion = (acc[a] as string) + pre + values[v]\n      // Bash drops empty results at the top level. Skip them before they count\n      // against `max`, so `max` bounds the number of *kept* results.\n      if (dropEmpties && !expansion) continue\n      if (length + expansion.length > maxLength) return out\n      out.push(expansion)\n      length += expansion.length\n    }\n  }\n  return out\n}\n\n// The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)\n// sequence body.\nfunction expandSequence(\n  body: string,\n  isAlphaSequence: boolean,\n  max: number,\n  maxLength: number,\n): string[] {\n  const n = body.split(/\\.\\./)\n  const N: string[] = []\n  // A sequence body always splits into two or three parts, but the compiler\n  // can't know that.\n  /* c8 ignore start */\n  if (n[0] === undefined || n[1] === undefined) {\n    return N\n  }\n  /* c8 ignore stop */\n  const x = numeric(n[0])\n  const y = numeric(n[1])\n  const width = Math.max(n[0].length, n[1].length)\n  let incr =\n    n.length === 3 && n[2] !== undefined ?\n      Math.max(Math.abs(numeric(n[2])), 1)\n    : 1\n  let test = lte\n  const reverse = y < x\n  if (reverse) {\n    incr *= -1\n    test = gte\n  }\n  const pad = n.some(isPadded)\n\n  let length = 0\n  for (let i = x; test(i, y) && N.length < max; i += incr) {\n    let c\n    if (isAlphaSequence) {\n      c = String.fromCharCode(i)\n      if (c === '\\\\') {\n        c = ''\n      }\n    } else {\n      c = String(i)\n      if (pad) {\n        const need = width - c.length\n        if (need > 0) {\n          const z = new Array(need + 1).join('0')\n          if (i < 0) {\n            c = '-' + z + c.slice(1)\n          } else {\n            c = z + c\n          }\n        }\n      }\n    }\n    if (length + c.length > maxLength) break\n    N.push(c)\n    length += c.length\n  }\n  return N\n}\n\nfunction expand_(\n  str: string,\n  max: number,\n  maxLength: number,\n  maxDepth: number,\n  depth: number,\n  maxRewrites: number,\n  isTop: boolean,\n): string[] {\n  // Too deeply nested to keep following: treat the rest as literal, the same\n  // way a group that cannot expand is already handled. Truncating rather than\n  // throwing keeps `expand` total, matching `max` and `maxLength`.\n  if (depth > maxDepth) {\n    return [str]\n  }\n\n  // Consume the string's top-level brace groups left to right, threading a\n  // running set of combined prefixes (`acc`). Expanding the tail iteratively -\n  // rather than recursing on `m.post` once per group - keeps the native stack\n  // depth constant, so deeply chained input (`'{a,b}'.repeat(3000)`) can no\n  // longer overflow the stack, and leaves a single accumulator whose size\n  // `maxLength` bounds directly (CVE-2026-14257).\n  let acc: string[] = ['']\n\n  // Bash drops empty results, but only when the *first* top-level group is a\n  // comma set - a sequence like `{a..\\}` may legitimately yield ''. The drop\n  // is on the final strings, so it is applied to whichever `combine` produces\n  // them (the one with no brace set left in the tail).\n  // How many times the `{a},b}` rewrite below has restarted the scan. Each pass\n  // re-reads the whole string, so leaving this unbounded is quadratic.\n  let rewrites = 0\n  let dropEmpties = false\n  let firstGroup = true\n\n  for (;;) {\n    const m = balanced('{', '}', str)\n\n    // No brace set left: the rest of the string is literal.\n    if (!m) {\n      return combine(acc, str, [''], max, maxLength, dropEmpties)\n    }\n\n    // no need to expand pre, since it is guaranteed to be free of brace-sets\n    const pre = m.pre\n\n    if (/\\$$/.test(pre)) {\n      acc = combine(\n        acc,\n        pre + '{' + m.body + '}',\n        [''],\n        max,\n        maxLength,\n        dropEmpties && !m.post.length,\n      )\n      firstGroup = false\n      if (!m.post.length) break\n      str = m.post\n      continue\n    }\n\n    const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n    const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(\n      m.body,\n    )\n    const isSequence = isNumericSequence || isAlphaSequence\n    const isOptions = m.body.indexOf(',') >= 0\n    if (!isSequence && !isOptions) {\n      // {a},b}\n      if (rewrites < maxRewrites && m.post.match(/,(?!,).*\\}/)) {\n        rewrites++\n        str = m.pre + '{' + m.body + escClose + m.post\n        isTop = true\n        continue\n      }\n      // Nothing here expands, so the whole remaining string is literal.\n      return combine(\n        acc,\n        pre + '{' + m.body + '}' + m.post,\n        [''],\n        max,\n        maxLength,\n        dropEmpties,\n      )\n    }\n\n    if (firstGroup) {\n      dropEmpties = isTop && !isSequence\n      firstGroup = false\n    }\n\n    let values: string[]\n    if (isSequence) {\n      values = expandSequence(m.body, isAlphaSequence, max, maxLength)\n    } else {\n      let n = parseCommaParts(m.body)\n      if (n.length === 1 && n[0] !== undefined) {\n        // x{{a,b}}y ==> x{a}y x{b}y\n        n = expand_(\n          n[0],\n          max,\n          maxLength,\n          maxDepth,\n          depth + 1,\n          maxRewrites,\n          false,\n        ).map(embrace)\n        //XXX is this necessary? Can't seem to hit it in tests.\n        /* c8 ignore start */\n        if (n.length === 1) {\n          acc = combine(\n            acc,\n            pre + n[0],\n            [''],\n            max,\n            maxLength,\n            dropEmpties && !m.post.length,\n          )\n          if (!m.post.length) break\n          str = m.post\n          continue\n        }\n        /* c8 ignore stop */\n      }\n\n      // Values that `combine` is going to drop as empty produce no result, so\n      // they must not count against `max` - otherwise `{a,,b}` with `max: 2`\n      // would stop at `['a', '']` and yield one result instead of two. Skipping\n      // them outright keeps `values` bounded while leaving `max` a bound on\n      // *kept* results.\n      let dropsEmpties = dropEmpties && !m.post.length && !pre\n      for (let d = 0; dropsEmpties && d < acc.length; d++) {\n        if (acc[d]) {\n          dropsEmpties = false\n        }\n      }\n\n      values = []\n      let valuesLength = 0\n      outer: for (let j = 0; j < n.length; j++) {\n        const expanded = expand_(\n          n[j] as string,\n          max,\n          maxLength,\n          maxDepth,\n          depth + 1,\n          maxRewrites,\n          false,\n        )\n        for (let k = 0; k < expanded.length; k++) {\n          const v = expanded[k] as string\n          if (dropsEmpties && !v) continue\n          if (\n            values.length >= max ||\n            valuesLength + v.length > maxLength\n          ) {\n            break outer\n          }\n          values.push(v)\n          valuesLength += v.length\n        }\n      }\n    }\n\n    acc = combine(\n      acc,\n      pre,\n      values,\n      max,\n      maxLength,\n      dropEmpties && !m.post.length,\n    )\n    if (!m.post.length) break\n    str = m.post\n  }\n\n  return acc\n}\n", "import type { Item } from './index.js'\n\n// One digit, or a class of digits from a to b.\nconst digit = (a: number, b: number): Item =>\n  a === b ?\n    { t: 'lit', ch: String(a) }\n  : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) }\n\nconst prefix = (d: number, alts: Item[][]) =>\n  alts.map(s => [digit(d, d), ...s])\n\n// The digit strings from a to b, which have the same length.\nconst fixed = (a: string, b: string): Item[][] => {\n  if (!a) return [[]]\n  let lo = +a[0]!\n  let hi = +b[0]!\n  const ra = a.slice(1)\n  const rb = b.slice(1)\n  if (lo === hi) return prefix(lo, fixed(ra, rb))\n  const zeros = '0'.repeat(ra.length)\n  const nines = '9'.repeat(ra.length)\n  const out: Item[][] = []\n  if (ra !== zeros) out.push(...prefix(lo++, fixed(ra, nines)))\n  const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb))\n  if (lo <= hi) {\n    out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))])\n  }\n  out.push(...last)\n  return out\n}\n\n// The numbers from a to b, where 0 <= a <= b. If width is set, each\n// one has leading zeros to make it that many digits.\nconst nonneg = (a: number, b: number, width: number): Item[][] => {\n  if (width) {\n    return fixed(\n      String(a).padStart(width, '0'),\n      String(b).padStart(width, '0'),\n    )\n  }\n  const out: Item[][] = []\n  for (let len = String(a).length; len <= String(b).length; len++) {\n    const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1))\n    const hi = Math.min(b, 10 ** len - 1)\n    out.push(...fixed(String(lo), String(hi)))\n  }\n  return out\n}\n\n/**\n * The strings that the bash brace expansion `{lo..hi}` makes, as\n * the alternatives of an `@(...)` extglob. Each one is a sequence of\n * digits and digit classes, so there are only a few of them, even for\n * a large range.\n *\n * If either end has a leading zero, such as `{01..10}`, each number\n * has leading zeros to make it as long as the longer end, counting a\n * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`.\n *\n * Returns undefined if either end is not a safe integer.\n */\nexport const numericRange = (\n  loStr: string,\n  hiStr: string,\n): Item[][] | undefined => {\n  let lo = Number(loStr)\n  let hi = Number(hiStr)\n  if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) return\n  if (lo > hi) [lo, hi] = [hi, lo]\n  const padded = /^-?0\\d/.test(loStr) || /^-?0\\d/.test(hiStr)\n  const width = padded ? Math.max(loStr.length, hiStr.length) : 0\n  const out: Item[][] = []\n  if (lo < 0) {\n    const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1)\n    out.push(...neg.map(s => [{ t: 'lit', ch: '-' } as Item, ...s]))\n  }\n  if (hi >= 0) out.push(...nonneg(Math.max(lo, 0), hi, width))\n  return out\n}\n", "// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n  '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n  '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n  '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n  '[:blank:]': ['\\\\p{Zs}\\\\t'],\n  '[:cntrl:]': ['\\\\p{Cc}'],\n  '[:digit:]': ['\\\\p{Nd}'],\n  '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n  '[:lower:]': ['\\\\p{Ll}'],\n  '[:print:]': ['\\\\p{C}', true],\n  '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n  '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n  '[:upper:]': ['\\\\p{Lu}'],\n  '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n  '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n  glob: string,\n  position: number,\n  nocase: boolean = false,\n  form?: Form,\n): ParseClassResult => {\n  // normalize one class member, if it stays one code point\n  const norm = (c: string) => {\n    const n = form ? c.normalize(form) : c\n    return [...n].length === 1 ? n : c\n  }\n  const pos = position\n  /* c8 ignore start */\n  if (glob.charAt(pos) !== '[') {\n    throw new Error('not in a brace expression')\n  }\n  /* c8 ignore stop */\n  const ranges: string[] = []\n  const negs: string[] = []\n\n  let i = pos + 1\n  let sawStart = false\n  let escaping = false\n  let negate = false\n  let endPos = pos\n  let rangeStart = ''\n  WHILE: while (i < glob.length) {\n    const c = String.fromCodePoint(glob.codePointAt(i)!)\n    if ((c === '!' || c === '^') && i === pos + 1) {\n      negate = true\n      i++\n      continue\n    }\n\n    if (c === ']' && sawStart && !escaping) {\n      endPos = i + 1\n      break\n    }\n\n    sawStart = true\n    if (c === '\\\\') {\n      if (!escaping) {\n        escaping = true\n        i++\n        continue\n      }\n      // escaped \\ char, fall through and treat like normal char\n    }\n    if (c === '[' && !escaping) {\n      // either a posix class, a collation equivalent, or just a [\n      for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n        if (glob.startsWith(cls, i)) {\n          // invalid, [a-[] is fine, but not [a-[:alpha]]\n          if (rangeStart) {\n            return [noMatch, glob.length - pos]\n          }\n          i += cls.length\n          if (neg) negs.push(unip)\n          else ranges.push(unip)\n          continue WHILE\n        }\n      }\n    }\n\n    // now it's just a normal character, effectively\n    escaping = false\n    const n = norm(c)\n    if (rangeStart) {\n      // throw this range away if it's not valid, but others\n      // can still match.\n      if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n        ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n      } else if (n === rangeStart) {\n        ranges.push(braceEscape(n))\n      }\n      rangeStart = ''\n      i += c.length\n      continue\n    }\n\n    // now might be the start of a range.\n    // can be either c-d or c-] or c] or c] at this point\n    if (glob.startsWith('-]', i + c.length)) {\n      ranges.push(braceEscape(n + '-'))\n      i += c.length + 1\n      continue\n    }\n    if (glob.startsWith('-', i + c.length)) {\n      rangeStart = n\n      i += c.length + 1\n      continue\n    }\n\n    // not the start of a range, just a single character\n    ranges.push(braceEscape(n))\n    i += c.length\n  }\n\n  if (endPos < i) {\n    // didn't see the end of the class, not a valid class,\n    // but might still be valid as a literal match.\n    return [noMatch, 0]\n  }\n\n  // if we got no ranges and no negates, then we have a range that\n  // cannot possibly match anything, and that poisons the whole glob\n  if (!ranges.length && !negs.length) {\n    return [noMatch, glob.length - pos]\n  }\n\n  const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n  const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n  const comb =\n    '^' +\n    (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n    : ranges.length ? sranges\n    : snegs)\n\n  return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n", "import { numericRange } from './numeric-range.js'\nimport { type Form, parseClass } from './parse-class.js'\n\nexport type { Form }\n\nexport type MatcherOptions = {\n  /** perform a case-insensitive match */\n  nocase?: boolean\n  /** do not treat strings starting with `.` specially */\n  dot?: boolean\n  /** do not match extglobs (treat them as normal strings) */\n  noext?: boolean\n  /**\n   * normalize unicode in the pattern and the tested strings, with\n   * this form. `true` means `'NFC'`.\n   */\n  normalize?: boolean | Form\n  /**\n   * A char that marks a numeric range in the pattern, as\n   * `..`, where `lo` and `hi` are integers. It\n   * matches the strings that the bash brace expansion `{..}`\n   * makes, such as `{1..100}` or `{001..100}`, without making each\n   * one. A mark is never escaped by a `\\` before it. Inside a `[...]`\n   * class, a mark is a char of the class.\n   */\n  rangeMark?: string\n}\n\n// parsed pattern items\nexport type Item =\n  | { t: 'lit'; ch: string }\n  | { t: 'any' | 'star' }\n  | { t: 'class'; re: RegExp }\n  | { t: 'ext'; type: string; alts: Item[][] }\n\n// extglob syntax tokens become literals if they are not part of a\n// closed extglob\nexport type Token =\n  Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' }\n\n// state machine nodes\nexport type NegNode = { t: 'neg'; id: number; sub: Node; next: Node }\nexport type SplitNode = { t: 'split'; id: number; out: Node[] }\nexport type Node =\n  | ({ t: 'lit'; id: number; next: Node } & Lit)\n  | { t: 'any' | 'star'; id: number; next: Node }\n  | { t: 'class'; id: number; re: RegExp; next: Node }\n  | SplitNode\n  | NegNode\n  | { t: 'match'; id: number }\n\n// the end of the pattern, or of a negated sub-pattern\nconst MATCH: Node = { t: 'match', id: 0 }\n\nconst extTypes = '!?+*@'\n\nconst lit = (ch: string): Item => ({ t: 'lit', ch })\n\nconst reEscape = (s: string) => s.replace(/[\\\\^$.*+?()[\\]{}|/]/g, '\\\\$&')\n\n// a RegExp that only matches `s`, with unicode case folding\nconst newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu')\n\n// foldRe for one literal char. The same chars are in most patterns,\n// so keep them. A RegExp without the `g` or `y` flag has no state to\n// share.\nconst foldCache = new Map()\nconst foldRe = (ch: string) => {\n  let re = foldCache.get(ch)\n  if (!re) {\n    re = newFoldRe(ch)\n    if (foldCache.size >= 1000) foldCache.clear()\n    foldCache.set(ch, re)\n  }\n  return re\n}\n\n/**\n * A literal char. With `nocase:true`, `re` folds case, and `ascii`\n * holds its results for ASCII chars, by char code: 1 for a match,\n * and 2 for not.\n */\nexport type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array }\n\nconst litMatch = (l: Lit, c: string) => {\n  if (c === l.ch) return true\n  if (!l.re) return false\n  const code = c.charCodeAt(0)\n  if (code >= 128) return l.re.test(c)\n  const ascii = (l.ascii ??= new Uint8Array(128))\n  ascii[code] ||= l.re.test(c) ? 1 : 2\n  return ascii[code] === 1\n}\n\nconst tokenize = (\n  p: string,\n  nocase: boolean,\n  noext: boolean,\n  form?: Form,\n  mark?: string,\n) => {\n  const toks: Token[] = []\n  for (let i = 0; i < p.length;) {\n    const c = String.fromCodePoint(p.codePointAt(i)!)\n    if (mark) {\n      // a \\ before a range would only escape its first char\n      const m = c === '\\\\' && p.startsWith(mark, i + 1) ? 1 : 0\n      if (m || c === mark) {\n        const start = i + m + mark.length\n        const end = p.indexOf(mark, start)\n        const r = /^(-?\\d+)\\.\\.(-?\\d+)$/.exec(p.slice(start, end))\n        const alts = end !== -1 && r && numericRange(r[1]!, r[2]!)\n        if (alts) {\n          toks.push({ t: 'ext', type: '@', alts })\n          i = end + mark.length\n          continue\n        }\n      }\n    }\n    if (c === '\\\\') {\n      // a trailing \\ is a literal \\\n      const e = p.codePointAt(i + 1)\n      const ch = e === undefined ? c : String.fromCodePoint(e)\n      toks.push(lit(ch))\n      i += 1 + ch.length\n      continue\n    }\n    if (c === '[') {\n      const [re, consumed] = parseClass(p, i, nocase, form)\n      if (consumed) {\n        toks.push({ t: 'class', re })\n        i += consumed\n        continue\n      }\n    }\n    if (!noext && extTypes.includes(c) && p[i + 1] === '(') {\n      toks.push({ t: 'open', type: c })\n      i += 2\n      continue\n    }\n    toks.push(\n      !noext && c === '|' ? { t: 'bar' }\n      : !noext && c === ')' ? { t: 'close' }\n      : c === '*' ? { t: 'star' }\n      : c === '?' ? { t: 'any' }\n      : lit(c),\n    )\n    i += c.length\n  }\n  return toks\n}\n\n// map each open token index to the index of its close token\nconst pair = (toks: Token[]) => {\n  const pairs = new Map()\n  const stack: number[] = []\n  toks.forEach((tok, i) => {\n    if (tok.t === 'open') stack.push(i)\n    else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i)\n  })\n  return pairs\n}\n\n// build the alternatives between start and end. An open token that\n// is not closed is never inside a closed extglob, so bar and close\n// tokens are only literal at the top level.\nconst build = (\n  toks: Token[],\n  pairs: Map,\n  start: number,\n  end: number,\n  top: boolean,\n): Item[][] => {\n  let seq: Item[] = []\n  const alts = [seq]\n  for (let i = start; i < end; i++) {\n    const tok = toks[i]!\n    const close = pairs.get(i)\n    if (tok.t === 'open' && close !== undefined) {\n      const sub = build(toks, pairs, i + 1, close, false)\n      seq.push({ t: 'ext', type: tok.type, alts: sub })\n      i = close\n    } else if (tok.t === 'bar' && !top) {\n      alts.push((seq = []))\n    } else if (tok.t === 'open') {\n      seq.push(lit(tok.type), lit('('))\n    } else if (tok.t === 'bar') {\n      seq.push(lit('|'))\n    } else if (tok.t === 'close') {\n      seq.push(lit(')'))\n    } else {\n      seq.push(tok)\n    }\n  }\n  return alts\n}\n\n// normalize each run of literal chars as one string, so that a char\n// and the combining marks after it compose (or decompose) together.\n// Syntax is already parsed, so a char that normalizes to a syntax\n// char (such as full-width `*` in NFKC) stays a literal.\nconst normalize = (items: Item[], form: Form): Item[] => {\n  const out: Item[] = []\n  let run = ''\n  const flush = () => {\n    for (const ch of run.normalize(form)) out.push(lit(ch))\n    run = ''\n  }\n  for (const it of items) {\n    if (it.t === 'lit') {\n      run += it.ch\n      continue\n    }\n    flush()\n    out.push(\n      it.t === 'ext' ?\n        { ...it, alts: it.alts.map(a => normalize(a, form)) }\n      : it,\n    )\n  }\n  flush()\n  return out\n}\n\n// the start node, and the number of node ids. Ids are dense, from 0\n// for the match node.\nconst compile = (\n  items: Item[],\n  nocase: boolean,\n): [start: Node, size: number] => {\n  let id = 1\n  const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out })\n  const seq = (items: Item[], next: Node): Node =>\n    items.reduceRight((next, it) => item(it, next), next)\n  const item = (it: Item, next: Node): Node => {\n    switch (it.t) {\n      case 'lit':\n        const re = nocase ? foldRe(it.ch) : undefined\n        return { t: 'lit', id: id++, ch: it.ch, re, next }\n      case 'any':\n      case 'star':\n        return { t: it.t, id: id++, next }\n      case 'class':\n        return { t: 'class', id: id++, re: it.re, next }\n    }\n    const alts = (next: Node) => it.alts.map(a => seq(a, next))\n    switch (it.type) {\n      case '@':\n        return split(alts(next))\n      case '?':\n        return split([next, ...alts(next)])\n      case '!':\n        return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }\n    }\n    // * and +, loop back after each match\n    const after = split([])\n    const entry = split(alts(after))\n    after.out.push(next, entry)\n    return it.type === '*' ? after : entry\n  }\n  const start = seq(items, MATCH)\n  return [start, id]\n}\n\n// one line per node, in the order that a walk from the start\n// reaches them. Edges point to node ids. The nodes of a negated\n// sub-pattern are indented under their negation.\nconst show = (start: Node): string => {\n  const lines: string[] = []\n  const seen = new Set()\n  const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id))\n  const walk = (n: Node, indent: string) => {\n    if (n.t === 'match' || seen.has(n)) return\n    seen.add(n)\n    const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`)\n    switch (n.t) {\n      case 'split':\n        line(`split -> ${n.out.map(ref).join(', ')}`)\n        for (const o of n.out) walk(o, indent)\n        return\n      case 'neg':\n        line(`!(${ref(n.sub)}) -> ${ref(n.next)}`)\n        walk(n.sub, indent + '  ')\n        return walk(n.next, indent)\n      case 'lit':\n        line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`)\n        break\n      case 'class':\n        line(`${n.re} -> ${ref(n.next)}`)\n        break\n      default:\n        line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`)\n    }\n    walk(n.next, indent)\n  }\n  walk(start, '')\n  return [`start -> ${ref(start)}`, ...lines].join('\\n')\n}\n\n// A thread inside a !(...) negation. It holds the threads of the\n// negated sub-pattern, started where the negation started. The\n// negation matches the chars so far if the sub-pattern does not.\ntype Run = { t: 'run'; neg: NegNode; state: State }\n\n// The threads at one position in the string. Each node thread is\n// only kept once, and runs with the same state are only kept once,\n// so that identical threads merge. The match node is not in\n// `threads`, because it can not step. It sets `match` instead.\nclass State {\n  // set by the Sim, to mark the nodes that this state has\n  gen: number\n  threads: Node[] = []\n  match = false\n  runs: Run[] = []\n  // the sorted ids of the threads, with 0 for a match, once the\n  // state is done\n  ids: number[] = []\n\n  constructor(gen: number) {\n    this.gen = gen\n  }\n\n  // no threads, so nothing more can match\n  get dead() {\n    return !this.threads.length && !this.match && !this.runs.length\n  }\n}\n\n// true if the two states hold the same threads\nconst sameState = (a: State, b: State): boolean => {\n  if (a.ids.length !== b.ids.length) return false\n  if (a.runs.length !== b.runs.length) return false\n  if (a.ids.some((id, i) => id !== b.ids[i])) return false\n  return a.runs.every(r =>\n    b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)),\n  )\n}\n\n/**\n * For each node id, the gen of the last state that has the node as\n * a thread, and of the last state that walked through it. A state is\n * built to the end before the states around it go on, and the nodes\n * of a negated sub-pattern are only in its states (other than the\n * match node, which is never marked). So one mark for each node is\n * enough to know if the state being built has it. The Sims of a\n * matcher never run at the same time, so they share one Marks.\n */\nexport type Marks = { has: Float64Array; seen: Float64Array; gen: number }\n\nconst marks = (size: number): Marks => ({\n  has: new Float64Array(size),\n  seen: new Float64Array(size),\n  gen: 0,\n})\n\nclass Sim {\n  // `.` and `..` only match literal dots, even with `dot:true`\n  dots: boolean\n  // the string starts with `.`, and `dot:true` is not set\n  dotStart: boolean\n  #marks: Marks\n\n  constructor(dots: boolean, dotStart: boolean, marks: Marks) {\n    this.dots = dots\n    this.dotStart = dotStart\n    this.#marks = marks\n  }\n\n  state() {\n    return new State(++this.#marks.gen)\n  }\n\n  // sort the ids of a state, once it has all of its threads\n  done(state: State) {\n    state.ids = state.threads.map(n => n.id).sort((a, b) => a - b)\n    if (state.match) state.ids.unshift(MATCH.id)\n    return state\n  }\n\n  // true the first time that the state walks through the node, so\n  // that loops in the graph stop\n  #visit(state: State, node: Node) {\n    const { seen } = this.#marks\n    if (seen[node.id] === state.gen) return false\n    seen[node.id] = state.gen\n    return true\n  }\n\n  #addThread(state: State, node: Node) {\n    const { has } = this.#marks\n    if (has[node.id] === state.gen) return false\n    has[node.id] = state.gen\n    state.threads.push(node)\n    return true\n  }\n\n  // wildcards only match a leading dot if `dot:true`. In a negated\n  // sub-pattern, this does not apply, because the negation itself\n  // can not match a leading dot.\n  restricted(i: number, top: boolean) {\n    return top && (this.dots || (this.dotStart && i === 0))\n  }\n\n  add(state: State, node: Node, i: number, top: boolean): void {\n    switch (node.t) {\n      case 'split':\n        if (!this.#visit(state, node)) return\n        for (const o of node.out) this.add(state, o, i, top)\n        return\n      case 'neg':\n        if (!this.#visit(state, node)) return\n        const sub = this.state()\n        this.add(sub, node.sub, i, false)\n        this.done(sub)\n        return this.addRun(\n          state,\n          { t: 'run', neg: node, state: sub },\n          i,\n          top,\n        )\n      case 'star':\n        // a * can not start a dotfile, even if it matches nothing\n        if (this.restricted(i, top)) return\n        if (this.#addThread(state, node))\n          this.add(state, node.next, i, top)\n        return\n      case 'match':\n        state.match = true\n        return\n      default:\n        this.#addThread(state, node)\n    }\n  }\n\n  addRun(state: State, run: Run, i: number, top: boolean) {\n    for (const r of state.runs) {\n      if (r.neg === run.neg && sameState(r.state, run.state)) return\n    }\n    state.runs.push(run)\n    if (!run.state.match) {\n      this.add(state, run.neg.next, i, top)\n    }\n  }\n\n  // the threads after char `c`, at index `i`\n  step(state: State, c: string, i: number, top: boolean): State {\n    const next = this.state()\n    for (const th of state.threads) {\n      switch (th.t) {\n        case 'lit':\n          if (litMatch(th, c)) {\n            this.add(next, th.next, i + 1, top)\n          }\n          break\n        case 'any':\n          if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top)\n          break\n        case 'class':\n          if (!this.restricted(i, top) && th.re.test(c)) {\n            this.add(next, th.next, i + 1, top)\n          }\n          break\n        case 'star':\n          if (!this.restricted(i, top)) this.add(next, th, i + 1, top)\n      }\n    }\n    if (!this.restricted(i, top)) {\n      for (const run of state.runs) {\n        // a sub-pattern with no threads can not match again, so the\n        // run stays the same\n        if (run.state.dead) {\n          this.addRun(next, run, i + 1, top)\n          continue\n        }\n        const sub = this.step(run.state, c, i, false)\n        this.addRun(\n          next,\n          { t: 'run', neg: run.neg, state: sub },\n          i + 1,\n          top,\n        )\n      }\n    }\n    return this.done(next)\n  }\n}\n\n// A canonical key for the threads in a state. States with the same\n// key hold the same threads, so they match the same strings.\nconst stateKey = (state: State): string => {\n  const ids = state.ids.join()\n  if (!state.runs.length) return ids\n  const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`)\n  return `${ids}|${runs.sort().join('|')}`\n}\n\n// A cached state of the simulation, and the states that each char\n// leads to.\ntype DState = {\n  state: State\n  match: boolean\n  // no threads, so nothing more can match\n  dead: boolean\n  // the next state for each ASCII char, by char code, and for the\n  // other chars\n  ascii?: (DState | undefined)[]\n  next: Map\n}\n\n// The cache can hold about this many chars of state keys and\n// transitions. When it is full, it is cleared, so that a pattern\n// can not use an unbounded amount of memory.\nconst DFA_BUDGET = 1 << 18\n\n// A cache of the states that the simulation reaches, built as the\n// matcher is used. Each char of a string is then one Map lookup,\n// once the states that it leads to are known.\n//\n// The dot rules only restrict the first char of a dotfile (strings\n// that are only `.` or `..` do not use the cache). So a dotfile\n// starts at its own state, which takes its first step with the\n// restriction, and every other state takes steps without it.\nclass Dfa {\n  #start: Node\n  #states = new Map()\n  #size = 0\n  #plain?: DState\n  #dotStart?: DState\n  #sim: Sim\n  #dotSim: Sim\n\n  constructor(start: Node, marks: Marks) {\n    this.#start = start\n    this.#sim = new Sim(false, false, marks)\n    this.#dotSim = new Sim(false, true, marks)\n  }\n\n  #make(state: State): DState {\n    return {\n      state,\n      match: state.match,\n      dead: state.dead,\n      next: new Map(),\n    }\n  }\n\n  #intern(state: State): DState {\n    const key = stateKey(state)\n    const found = this.#states.get(key)\n    if (found) return found\n    if (this.#size > DFA_BUDGET) this.#clear()\n    const d = this.#make(state)\n    this.#states.set(key, d)\n    this.#size += key.length + 1\n    return d\n  }\n\n  #clear() {\n    this.#states.clear()\n    this.#size = 0\n    this.#plain = undefined\n    this.#dotStart = undefined\n  }\n\n  start(dotStart: boolean): DState {\n    if (dotStart) {\n      if (this.#dotStart) return this.#dotStart\n      const state = this.#dotSim.state()\n      this.#dotSim.add(state, this.#start, 0, true)\n      return (this.#dotStart = this.#make(this.#dotSim.done(state)))\n    }\n    if (this.#plain) return this.#plain\n    const state = this.#sim.state()\n    this.#sim.add(state, this.#start, 0, true)\n    return (this.#plain = this.#intern(this.#sim.done(state)))\n  }\n\n  // the next state, after a miss in `d.ascii`\n  next(d: DState, c: string): DState {\n    const code = c.charCodeAt(0)\n    const found = code < 128 ? undefined : d.next.get(c)\n    if (found) return found\n    // the dotfile start is not in the cache, so it is never shared\n    const n =\n      d === this.#dotStart ?\n        this.#intern(this.#dotSim.step(d.state, c, 0, true))\n      : this.#intern(this.#sim.step(d.state, c, 1, true))\n    if (code < 128) {\n      if (!d.ascii) {\n        d.ascii = new Array(128)\n        this.#size += 128\n      }\n      d.ascii[code] = n\n    } else {\n      d.next.set(c, n)\n    }\n    this.#size++\n    return n\n  }\n}\n\n/**\n * A node in a graph with no splits or negations. Such a graph is a\n * chain of nodes that each match one char, or a `*`.\n */\nexport type LinearNode = Exclude<\n  Node,\n  SplitNode | NegNode | { t: 'match' }\n>\n\n// the nodes in order, if the graph is a single chain\nconst linear = (start: Node): LinearNode[] | undefined => {\n  const nodes: LinearNode[] = []\n  for (let n = start; n.t !== 'match'; n = n.next) {\n    if (n.t === 'split' || n.t === 'neg') return undefined\n    nodes.push(n)\n  }\n  return nodes\n}\n\n// Match a chain of nodes. Each node other than `*` matches exactly\n// one char, so on a failure it is enough to go back to the last `*`\n// and let it match one more char. This takes at most\n// nodes.length * chars.length steps.\nconst testLinear = (\n  nodes: LinearNode[],\n  chars: ArrayLike,\n  start: number,\n  end: number,\n) => {\n  let ni = 0\n  let ci = start\n  let starNi = -1\n  let starCi = 0\n  while (ci < end) {\n    const n = nodes[ni]\n    if (n?.t === 'star') {\n      starNi = ni++\n      starCi = ci\n      continue\n    }\n    const c = chars[ci]!\n    if (\n      n &&\n      (n.t === 'any' ||\n        (n.t === 'lit' && litMatch(n, c)) ||\n        (n.t === 'class' && n.re.test(c)))\n    ) {\n      ni++\n      ci++\n      continue\n    }\n    if (starNi === -1) return false\n    ni = starNi + 1\n    ci = ++starCi\n  }\n  while (nodes[ni]?.t === 'star') ni++\n  return ni === nodes.length\n}\n\n// The least and most chars that the items can match. These are only\n// bounds: a negation can match a string of any length, so it counts\n// as 0 to Infinity.\nconst lengths = (items: Item[]): [min: number, max: number] => {\n  let min = 0\n  let max = 0\n  for (const it of items) {\n    const [lo, hi] = itemLengths(it)\n    min += lo\n    max += hi\n  }\n  return [min, max]\n}\n\nconst itemLengths = (it: Item): [min: number, max: number] => {\n  if (it.t === 'star') return [0, Infinity]\n  if (it.t !== 'ext') return [1, 1]\n  if (it.type === '!') return [0, Infinity]\n  const alts = it.alts.map(lengths)\n  const min = Math.min(...alts.map(a => a[0]))\n  const max = Math.max(...alts.map(a => a[1]))\n  // a loop of alternatives that only match the empty string is empty\n  const loop = max === 0 ? 0 : Infinity\n  return (\n    it.type === '@' ? [min, max]\n    : it.type === '?' ? [0, max]\n    : it.type === '*' ? [0, loop]\n    : [min, loop]\n  )\n}\n\n// true if the chars from `start` match the literals\nconst hasAffix = (\n  lits: Lit[],\n  chars: ArrayLike,\n  start: number,\n) => {\n  for (let j = 0; j < lits.length; j++) {\n    if (!litMatch(lits[j]!, chars[start + j]!)) return false\n  }\n  return true\n}\n\n// a `/`, or half of a surrogate pair\nconst slashOrSurrogate = /[/\\ud800-\\udfff]/\nconst surrogate = /[\\ud800-\\udfff]/\n\n// a string can be indexed by code point, unless it has surrogate\n// pairs\nconst codePoints = (s: string): ArrayLike =>\n  surrogate.test(s) ? [...s] : s\n\nconst noSlash = (s: string) => {\n  if (s.includes('/')) {\n    throw new Error('can only match a single path portion, got: ' + s)\n  }\n}\n\nexport class Matcher {\n  pattern: string\n  options: MatcherOptions\n  #start: Node\n  // the number of node ids\n  #size: number\n  #marks?: Marks\n  // the Sim for strings that are only `.` or `..`\n  #dotsSim?: Sim\n  // the string to compare, if the pattern has no magic. With\n  // `nocase:true`, the RegExp that folds case is made when it is\n  // first used.\n  #literal?: string\n  #literalFold = false\n  #literalRe?: RegExp\n  // the nodes between the prefix and suffix, if the graph is a\n  // single chain\n  #linear?: LinearNode[]\n  // the linear nodes are only `*` and `?`, so the length bounds and\n  // the prefix and suffix decide the match\n  #wild = false\n  // the least and most chars that a match can have\n  #min = 0\n  #max = Infinity\n  // the literals that a match must start and end with. Each one\n  // matches exactly one char, and they are distinct items in the\n  // pattern, so a string that does not have them can not match.\n  #prefix: Lit[] = []\n  #suffix: Lit[] = []\n  // the prefix and suffix as strings, if they do not fold case\n  #prefixStr?: string\n  #suffixStr?: string\n  // there is a prefix or suffix to check\n  #affix = false\n  #dfa?: Dfa\n  #form?: Form\n\n  constructor(pattern: string, options: MatcherOptions = {}) {\n    if (pattern.includes('/')) {\n      throw new Error(\n        'can only match a single path portion, got pattern: ' + pattern,\n      )\n    }\n    this.pattern = pattern\n    this.options = options\n    const { nocase = false, noext = false, normalize: n } = options\n    this.#form = n === true ? 'NFC' : n || undefined\n    // a pattern that is only an empty extglob is a literal string,\n    // except for `!()`, which matches any non-empty string\n    const literal = /^[?*+@]\\(\\)$/.test(pattern)\n    const toks = tokenize(\n      pattern,\n      nocase,\n      noext || literal,\n      this.#form,\n      options.rangeMark,\n    )\n    let [items] = build(toks, pair(toks), 0, toks.length, true)\n    if (this.#form) items = normalize(items!, this.#form)\n    const [start, size] = compile(items!, nocase)\n    this.#start = start\n    this.#size = size\n    if (items!.every(it => it.t === 'lit')) {\n      this.#literal = items!.map(it => it.ch).join('')\n      this.#literalFold = nocase\n    } else {\n      const lit = (it: Item): Lit | undefined =>\n        it.t !== 'lit' ? undefined\n        : nocase ? { ch: it.ch, re: foldRe(it.ch) }\n        : { ch: it.ch }\n      for (const it of items!) {\n        const l = lit(it)\n        if (!l) break\n        this.#prefix.push(l)\n      }\n      for (let j = items!.length - 1; j >= 0; j--) {\n        const l = lit(items![j]!)\n        if (!l) break\n        this.#suffix.unshift(l)\n      }\n      this.#affix = !!(this.#prefix.length || this.#suffix.length)\n      if (!nocase) {\n        this.#prefixStr = this.#prefix.map(l => l.ch).join('')\n        this.#suffixStr = this.#suffix.map(l => l.ch).join('')\n      }\n      this.#linear = linear(this.#start)?.slice(\n        this.#prefix.length,\n        -this.#suffix.length || undefined,\n      )\n      this.#wild = !!this.#linear?.every(\n        n => n.t === 'star' || n.t === 'any',\n      )\n      const [min, max] = lengths(items!)\n      this.#min = min\n      this.#max = max\n    }\n  }\n\n  test(s: string): boolean {\n    // The `/` check uses the string as given, so with normalization it\n    // is a separate step. Otherwise, one scan finds both a `/` and the\n    // surrogate pairs that stop the string being indexed by code point.\n    if (this.#form) {\n      noSlash(s)\n      return this.#test(s.normalize(this.#form))\n    }\n    if (slashOrSurrogate.test(s)) {\n      noSlash(s)\n      return this.#test(s, [...s])\n    }\n    return this.#test(s, s)\n  }\n\n  /**\n   * The same as {@link Matcher#test}, but the string is not checked\n   * for `/` chars, so the result for a string that has one is not\n   * defined. Only use it for a string that is known to be one path\n   * portion, such as a part of a path that was split on `/`. It can\n   * be faster, because some patterns do not need to look at each char\n   * of the string.\n   */\n  testUnchecked(s: string): boolean {\n    return this.#test(this.#form ? s.normalize(this.#form) : s)\n  }\n\n  // Test a string that has no `/`. `chars` indexes it by code point.\n  // If it is not given, it is only found if a step needs it.\n  #test(s: string, chars?: ArrayLike): boolean {\n    if (this.#literal !== undefined) {\n      return this.#literalFold ?\n          (this.#literalRe ??= newFoldRe(this.#literal)).test(s)\n        : s === this.#literal\n    }\n    // the length check means that the prefix and suffix do not\n    // overlap. Without the chars, the length in code points is from\n    // half of the UTF-16 length (if each one is a surrogate pair) to\n    // all of it, which is often enough to know.\n    const min = this.#min\n    const max = this.#max\n    if (chars === undefined) {\n      const most = s.length\n      const least = (most + 1) >> 1\n      if (most < min || least > max) return false\n      if (least < min || most > max) chars = codePoints(s)\n    }\n    if (\n      chars !== undefined &&\n      (chars.length < min || chars.length > max)\n    ) {\n      return false\n    }\n    const prefix = this.#prefix.length\n    if (this.#affix) {\n      if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {\n        if (\n          !s.startsWith(this.#prefixStr) ||\n          !s.endsWith(this.#suffixStr)\n        ) {\n          return false\n        }\n      } else {\n        chars ??= codePoints(s)\n        const end = chars.length - this.#suffix.length\n        if (\n          !hasAffix(this.#prefix, chars, 0) ||\n          !hasAffix(this.#suffix, chars, end)\n        ) {\n          return false\n        }\n      }\n    }\n    const dotStart = !this.options.dot && s.startsWith('.')\n    if (this.#linear) {\n      // `.` and `..` only match literal dots, even with `dot:true`\n      if (s === '.' || s === '..') return false\n      // only a literal can match the leading dot. A `*` can not\n      // start a dotfile, even if it matches nothing.\n      if (dotStart && !prefix) return false\n      if (this.#wild) return true\n      chars ??= codePoints(s)\n      const end = chars.length - this.#suffix.length\n      return testLinear(this.#linear, chars, prefix, end)\n    }\n    chars ??= codePoints(s)\n    if (s === '.' || s === '..') {\n      this.#marks ??= marks(this.#size)\n      const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks))\n      const start = sim.state()\n      sim.add(start, this.#start, 0, true)\n      let state = sim.done(start)\n      for (let i = 0; i < chars.length; i++) {\n        state = sim.step(state, chars[i]!, i, true)\n      }\n      return state.match\n    }\n    this.#marks ??= marks(this.#size)\n    const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks))\n    let d = dfa.start(dotStart)\n    // read char codes from the string, so that a one-char string is\n    // only made for a cache miss\n    const str = chars === s\n    for (let i = 0; i < chars.length; i++) {\n      if (d.dead) return false\n      const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0)\n      d = d.ascii?.[code] ?? dfa.next(d, chars[i]!)\n    }\n    return d.match\n  }\n\n  /** a readable listing of the state machine */\n  toString(): string {\n    return show(this.#start)\n  }\n}\n", "const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: unknown) => void = (\n  pattern: unknown,\n): asserts pattern is string => {\n  if (typeof pattern !== 'string') {\n    throw new TypeError('invalid pattern')\n  }\n\n  if (pattern.length > MAX_PATTERN_LENGTH) {\n    throw new TypeError('pattern is too long')\n  }\n}\n", "import type { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character.  In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n */\nexport const escape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = false,\n  }: Pick = {},\n) => {\n  // don't need to escape +@! because we escape the parens\n  // that make those magic, and escaping ! as [!] isn't valid,\n  // because [!]] is a valid glob class meaning not ']'.\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/[?*()[\\]{}]/g, '[$&]')\n      : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/[?*()[\\]]/g, '[$&]')\n    : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n", "import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = true,\n  }: Pick = {},\n) => {\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/\\[([^/\\\\])\\]/g, '$1')\n      : s\n          .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n          .replace(/\\\\([^/])/g, '$1')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n    : s\n        .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n        .replace(/\\\\([^/{}])/g, '$1')\n}\n", "import { expand } from 'brace-expansion'\nimport { Matcher, type Form } from '@isaacs/nonrecursive-glob-match'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\nexport type Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  /** do not expand `{x,y}` style braces */\n  nobrace?: boolean\n  /** do not treat patterns starting with `#` as a comment */\n  nocomment?: boolean\n  /** do not treat patterns starting with `!` as a negation */\n  nonegate?: boolean\n  /** treat `**` the same as `*` */\n  noglobstar?: boolean\n  /** do not expand extglobs like `+(a|b)` */\n  noext?: boolean\n  /** return the pattern if nothing matches */\n  nonull?: boolean\n  /** treat `\\\\` as a path separator, not an escape character */\n  windowsPathsNoEscape?: boolean\n  /**\n   * inverse of {@link MinimatchOptions.windowsPathsNoEscape}\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n  /**\n   * Compare a partial path to a pattern. As long as the parts\n   * of the path that are present are not contradicted by the\n   * pattern, it will be treated as a match. This is useful in\n   * applications where you're walking through a folder structure,\n   * and don't yet have the full path, but want to ensure that you\n   * do not walk down paths that can never be a match.\n   */\n  partial?: boolean\n  /** allow matches that start with `.` even if the pattern does not */\n  dot?: boolean\n  /** ignore case */\n  nocase?: boolean\n  /** ignore case only in wildcard patterns */\n  nocaseMagicOnly?: boolean\n  /**\n   * Normalize unicode in the pattern and in each portion of the\n   * tested paths, with this form. `true` means `'NFC'`.\n   */\n  normalize?: boolean | Form\n  /** consider braces to be \"magic\" for the purpose of `hasMagic` */\n  magicalBraces?: boolean\n  /**\n   * If set, then patterns without slashes will be matched\n   * against the basename of the path if it contains slashes.\n   * For example, `a?b` would match the path `/xyz/123/acb`, but\n   * not `/xyz/acb/123`.\n   */\n  matchBase?: boolean\n  /** invert the results of negated matches */\n  flipNegate?: boolean\n  /** do not collapse multiple `/` into a single `/` */\n  preserveMultipleSlashes?: boolean\n  /**\n   * A number indicating the level of optimization that should be done\n   * to the pattern prior to parsing and using it for matches.\n   * At level 2 or higher, throws RangeError if splitting `**` and `..`\n   * would make more than `braceExpandMax` patterns, or add more than\n   * 1,000,000 path portions.\n   */\n  optimizationLevel?: number\n  /** operating system platform */\n  platform?: Platform\n  /**\n   * When a pattern starts with a UNC path or drive letter, and in\n   * `nocase:true` mode, do not convert the root portions of the\n   * pattern into a case-insensitive regular expression, and instead\n   * leave them as strings.\n   *\n   * This is the default when the platform is `win32` and\n   * `nocase:true` is set.\n   */\n  windowsNoMagicRoot?: boolean\n  /**\n   * max number of `{...}` patterns to expand. Default 100_000.\n   *\n   * At `optimizationLevel` 2 or higher, this also limits the\n   * patterns made when `**` is followed by `..`. Over this limit,\n   * construction throws a RangeError.\n   */\n  braceExpandMax?: number\n  /**\n   * Max number of non-adjacent `**` patterns to recursively walk down.\n   *\n   * The default of 200 is almost certainly high enough for most purposes,\n   * and can handle absurdly excessive patterns.\n   */\n  maxGlobstarRecursion?: number\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return cachedMinimatch(pattern, options).match(p)\n}\n\n// The Minimatch objects that minimatch() used most recently. A Map\n// keeps its keys in the order they were set, so the first key is the\n// one used least recently.\nconst cache = new Map()\nconst cacheMax = 256\nconst cachedMinimatch = (pattern: string, options: MinimatchOptions) => {\n  const key = pattern + '\\0' + JSON.stringify(options)\n  let mm = cache.get(key)\n  if (mm) {\n    cache.delete(key)\n  } else {\n    // a copy, so a later change to the options can not change it\n    mm = new Minimatch(pattern, { ...options })\n    if (cache.size >= cacheMax) {\n      cache.delete(cache.keys().next().value as string)\n    }\n  }\n  cache.set(key, mm)\n  return mm\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process ?\n    process.env?.__MINIMATCH_TESTING_PLATFORM__ || process.platform\n  : 'posix') as Platform\n\nexport type Sep = '\\\\' | '/'\n\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep =\n  defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\nexport const filter =\n  (pattern: string, options: MinimatchOptions = {}) =>\n  (p: string) =>\n    minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) =>\n      orig.defaults(ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (\n      list: string[],\n      pattern: string,\n      options: MinimatchOptions = {},\n    ) => orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  return expand(pattern, { max: options.braceExpandMax })\n}\nminimatch.braceExpand = braceExpand\n\n// A numeric range with at least this many values is matched as one\n// pattern portion, rather than expanded. For a glob walk, that is\n// one directory read, in place of a stat for each value.\nconst RANGE_MIN = 100\n// a {lo..hi} range that is not escaped, and not a ${...} variable\nconst rangeRe = /(? {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\n\n// Index of the `]` that closes the class that starts at `start`,\n// or -1 if it is not closed. Posix classes such as `[:alpha:]` are\n// not skipped, so this can find a `]` before the real end. That\n// only makes a class look less like a literal.\nconst classEnd = (pattern: string, start: number) => {\n  let i = start + 1\n  if (pattern.charAt(i) === '!' || pattern.charAt(i) === '^') i++\n  let sawStart = false\n  for (; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === ']' && sawStart) return i\n    sawStart = true\n    if (c === '\\\\') i++\n  }\n  return -1\n}\n\n// If a path portion pattern has no magic, return the string it\n// matches. Otherwise, return undefined. This can report magic for\n// a pattern that is in fact literal (eg, `[]`), but never the\n// reverse, so a string result is always safe to compare directly.\nconst literal = (pattern: string, noext: boolean): string | undefined => {\n  if (!noext && (pattern === '+()' || pattern === '@()')) return pattern\n  let lit = ''\n  for (let i = 0; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      // a trailing \\ is a literal \\\n      lit += pattern.charAt(++i) || c\n    } else if (c === '*' || c === '?') {\n      return undefined\n    } else if (c === '[') {\n      const close = classEnd(pattern, i)\n      if (close === -1) {\n        // not closed, so the [ is a literal\n        lit += c\n        continue\n      }\n      // a class of one char, such as `[*]` or `[\\b]`, is a literal\n      let body = pattern.slice(i + 1, close)\n      if (body.startsWith('\\\\')) body = body.slice(1)\n      if ([...body].length !== 1 || '!^'.includes(pattern.charAt(i + 1))) {\n        return undefined\n      }\n      lit += body\n      i = close\n    } else if (\n      !noext &&\n      '+@!'.includes(c) &&\n      pattern.charAt(i + 1) === '(' &&\n      pattern.includes(')', i + 2)\n    ) {\n      return undefined\n    } else {\n      lit += c\n    }\n  }\n  return lit\n}\n\n// True if the portion pattern has the same meaning as an alternative\n// inside `@(...)`. It must not have a `|` or `)` that is not in a\n// closed extglob (those are literal at the top level), an extglob\n// that is not closed (the `)` of the `@(...)` would close it), or a\n// trailing `\\` (it would escape the next `|`). A pattern that is\n// only an empty extglob, such as `?()`, is literal on its own, but\n// not in `@(...)`. Posix classes such as `[:alpha:]` can hide a `]`\n// from classEnd, so patterns with them are not merged.\nconst extSafe = (pattern: string) => {\n  if (/^[?*+@]\\(\\)$/.test(pattern) || pattern.includes('[:')) return false\n  let depth = 0\n  for (let i = 0; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      if (++i === pattern.length) return false\n    } else if (c === '[') {\n      const close = classEnd(pattern, i)\n      if (close !== -1) i = close\n    } else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') {\n      depth++\n      i++\n    } else if (c === ')') {\n      if (!depth--) return false\n    } else if (c === '|' && !depth) {\n      return false\n    }\n  }\n  return !depth\n}\n\n// The last path that Minimatch#match split, and its parts. A path is\n// often tested against many patterns in a row (such as a list of\n// ignore patterns), so this saves splitting it again. The parts are\n// never changed, so they can be shared.\nlet lastSplit: SplitPath | undefined\n\n/**\n * A path that Minimatch#match split, with the settings that the split\n * depends on. `resolved` is the parts after optimizationLevel 2 has\n * resolved `.` and `..` in them, which only depends on the same\n * settings, once a level 2 Minimatch has needed them.\n */\nexport type SplitPath = {\n  f: string\n  isWindows: boolean\n  preserveMultipleSlashes: boolean\n  normalize: Form | undefined\n  parts: string[]\n  resolved?: string[]\n}\n\n// The last path that Minimatch#match checked before splitting it. If\n// the same path is checked again, it is being tested against many\n// patterns, so it is split and the parts are kept for the others.\nlet lastChecked: string | undefined\n\nexport type ParseReturnFiltered = string | Matcher | typeof GLOBSTAR\n\n/**\n * The rows that Minimatch#match can match without splitting the path:\n * `**` and one more portion (`tail`), a portion with `**` on each side\n * of it (`mid`), a portion and then `**` (`head`), or one portion that\n * matches the basename of the path, with matchBase (`base`).\n */\nexport type RowShape = 'tail' | 'mid' | 'head' | 'base'\n\n// true if a pattern portion that is not ** matches a path portion.\n// An empty path portion only matches an empty pattern portion. A path\n// portion never has a `/`, so the Matcher does not need to check it.\nconst portionMatch = (p: string | Matcher, f: string) =>\n  typeof p === 'string' ? f === p : f !== '' && p.testUnchecked(f)\n\n// Where the last portion of a row matches in a path: the start of the\n// last portion of the path, or of the one before a trailing `/`. -1 if\n// it matches neither.\nconst endIndex = (\n  p: string | Matcher,\n  last: string,\n  lastStart: number,\n  prev: string | undefined,\n  prevStart: number,\n) =>\n  portionMatch(p, last) ? lastStart\n  : prev !== undefined && portionMatch(p, prev) ? prevStart\n  : -1\n\nconst isDots = (p: string) => p === '.' || p === '..'\n\n// a Windows drive letter portion, like `c:`\nconst isDrive = (p: ParseReturn | undefined) =>\n  typeof p === 'string' && /^[a-z]:$/i.test(p)\n\n// true for the `UNC` portion of a long UNC root, //?/UNC/host/share\nconst isLongUNC = (p: ParseReturn | undefined) =>\n  typeof p === 'string' && /^unc$/i.test(p)\n\n// The index of the host in a row or split path that starts with a\n// Windows UNC root: 2 for `//host/share`, and 4 for\n// `//?/UNC/host/share`. Otherwise -1. `//?/c:` is not one.\nconst uncHost = (p: ParseReturn[]) => {\n  if (p[0] !== '' || p[1] !== '') return -1\n  const h =\n    p[2] !== '?' ? 2\n    : isLongUNC(p[3]) ? 4\n    : -1\n  const host = p[h]\n  const share = p[h + 1]\n  return (\n      h !== -1 &&\n        host !== undefined &&\n        host !== '' &&\n        host !== GLOBSTAR &&\n        share !== undefined &&\n        share !== '' &&\n        share !== GLOBSTAR\n    ) ?\n      h\n    : -1\n}\n\n// true if ** can walk the path portion: not `.` or `..`, and not a\n// dotfile unless `dot` is set\nconst walkable = (p: string, dot: boolean) =>\n  !isDots(p) && (dot || !p.startsWith('.'))\n\n// True if a portion of the path from `start` to `end` can not be\n// walked by **: one that starts with `.`, or with `dot`, one that is\n// `.` or `..`. `start` is the start of a portion, and `end` is the end\n// of the path, or just after a separator.\nconst dotPortion = (\n  f: string,\n  start: number,\n  end: number,\n  dot: boolean,\n  sep: PathSeps,\n) => {\n  for (let k = start; k < end;) {\n    if (f.charCodeAt(k) === 46) {\n      if (!dot) return true\n      const n = f.charCodeAt(k + 1) === 46 ? k + 2 : k + 1\n      if (n >= end || isSep(f.charCodeAt(n), sep)) return true\n    }\n    // the start of the next portion, after any run of separators\n    const s = nextSep(f, k, sep)\n    if (s === -1) return false\n    k = s + 1\n    while (k < end && isSep(f.charCodeAt(k), sep)) k++\n  }\n  return false\n}\n\n/**\n * The separators that a path has: only `/`, only `\\` (a Windows path\n * with no `/`), or both. Scanning for the ones it has is faster.\n */\nexport type PathSeps = '/' | '\\\\' | 'both'\n\nconst isSep = (c: number, sep: PathSeps) =>\n  sep === '/' ? c === 47\n  : sep === '\\\\' ? c === 92\n  : c === 47 || c === 92\n\n// the index of the first separator at or after `from`, or -1\nconst nextSep = (f: string, from: number, sep: PathSeps) => {\n  if (sep !== 'both') return f.indexOf(sep, from)\n  const s = f.indexOf('/', from)\n  const b = f.indexOf('\\\\', from)\n  return (\n    s === -1 ? b\n    : b === -1 ? s\n    : Math.min(s, b)\n  )\n}\n\n// the index of the last separator at or before `from`, or -1\nconst lastSep = (f: string, from: number, sep: PathSeps) =>\n  sep !== 'both' ?\n    f.lastIndexOf(sep, from)\n  : Math.max(f.lastIndexOf('/', from), f.lastIndexOf('\\\\', from))\n\n/**\n * A pattern row split on its first and last `**`, from a start\n * index. Each body segment has the number of path portions that it\n * and the ones after it need, to find the last index where it can\n * start in a path.\n */\nexport type GlobstarParts = {\n  head: ParseReturn[]\n  body: ParseReturn[]\n  tail: ParseReturn[]\n  segments: [segment: ParseReturn[], need: number][]\n}\nexport type ParseReturn = ParseReturnFiltered | false\n\n// What parse() returns in place of a Matcher while make() builds and\n// merges the rows. Most of the Matchers in rows that are merged would\n// never be used, so they are only made for the rows that are left.\nconst PENDING = {} as Matcher\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n  maxGlobstarRecursion: number\n  // the path can be checked against the last portion, and the string\n  // portions, of each row before it is split. See #canMatch.\n  #endCheck: boolean\n  #literalCheck: boolean\n  // level 2 resolves `.` and `..` portions in the path\n  #level2: boolean\n  // the unicode normalization form, if any\n  #form: Form | undefined\n  // the string portions of each row in the set\n  #literals: string[][] = []\n  // the rows that #canMatch can match without splitting the path\n  #shapes: (RowShape | undefined)[] = []\n  // the rows whose last portion can be checked against the path's\n  #endRows: boolean[] = []\n  // brace expansion can make the same portion in many rows, so they\n  // share one Matcher, and the states that it caches\n  #matchers = new Map()\n  // parse() returns PENDING in place of a Matcher\n  #pending = false\n  // the char that marks numeric ranges in globSet, if any\n  #rangeMark?: string\n  // the GlobstarParts of each pattern row, by start index and partial\n  #globstarParts = new WeakMap()\n\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    // avoid the annoying deprecation flag lol\n    const awe = ('allowWindow' + 'sEscape') as keyof MinimatchOptions\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options[awe] === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined ?\n        options.windowsNoMagicRoot\n      : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n    this.#endCheck = !this.preserveMultipleSlashes\n    this.#level2 = (options.optimizationLevel ?? 1) >= 2\n    const n = options.normalize\n    this.#form = n === true ? 'NFC' : n || undefined\n\n    // make the set of Matchers etc.\n    this.make()\n\n    // On Windows, the portions of a row up to its drive letter or UNC\n    // share are skipped or compared without case, if the path has one\n    // too. So the checks only use the portions after it.\n    const drives = this.set.map(row => this.#rootIndex(row))\n    this.#endRows = this.set.map(\n      (row, r) => this.#endCheck && row.length - 1 > drives[r]!,\n    )\n    // with the end check, the last portion is already checked\n    this.#literals = this.set.map((row, r) => {\n      const end = this.#endRows[r] ? row.length - 1 : row.length\n      const lits = row\n        .slice(drives[r]! + 1, end)\n        .filter((p): p is string => typeof p === 'string' && !!p)\n      return [...new Set(lits)]\n    })\n    this.#literalCheck = this.#literals.some(l => l.length)\n    this.#shapes = this.set.map((row, r) => {\n      const [p0, p1, p2] = row\n      if (this.#endRows[r] && row.length === 2) {\n        if (p0 === GLOBSTAR && p1 !== GLOBSTAR) return 'tail'\n      }\n      // the basename of a path that is split on / is its last portion,\n      // or the one before a trailing /, the same as the end check\n      if (\n        this.#endRows[r] &&\n        options.matchBase &&\n        row.length === 1 &&\n        p0 !== GLOBSTAR &&\n        p0 !== ''\n      ) {\n        return 'base'\n      }\n      // the portion must not be a root, or '', which can be a\n      // different portion on Windows (where //x paths get an extra '')\n      if (!this.#endCheck || drives[r] !== -1) return undefined\n      if (\n        row.length === 3 &&\n        p0 === GLOBSTAR &&\n        p2 === GLOBSTAR &&\n        p1 !== GLOBSTAR &&\n        p1 !== '' &&\n        // the portion between is only matched below this limit\n        this.maxGlobstarRecursion > 0\n      ) {\n        return 'mid'\n      }\n      if (\n        row.length === 2 &&\n        p1 === GLOBSTAR &&\n        p0 !== GLOBSTAR &&\n        p0 !== ''\n      ) {\n        return 'head'\n      }\n      return undefined\n    })\n  }\n\n  // a string portion of a pattern, normalized if the option is set\n  #norm(p: string) {\n    return this.#form ? p.normalize(this.#form) : p\n  }\n\n  // On Windows, the index of the last root portion of a row, as\n  // #matchRow finds it: 0 for `c:/...`, 3 for `//?/c:/...` and\n  // `//host/share/...`, and 5 for `//?/UNC/host/share/...`. Otherwise\n  // -1.\n  #rootIndex(row: ParseReturn[]) {\n    if (!this.isWindows) return -1\n    if (isDrive(row[0])) return 0\n    const uncDrive =\n      row[0] === '' && row[1] === '' && row[2] === '?' && isDrive(row[3])\n    if (uncDrive) return 3\n    const h = uncHost(row)\n    return h === -1 ? -1 : h + 1\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.#expandBraces())]\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be Matchers, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.#slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n\n    // glob --> Matchers\n    this.#pending = true\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path. The root of a long UNC\n        // path, //?/UNC/host/share, is 6 portions.\n        const n = s[2] === '?' && isLongUNC(s[3]) ? 6 : 4\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          s.slice(3, n).every(p => !globMagic.test(p))\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [\n            ...s.slice(0, n).map(p => this.#norm(p)),\n            ...s.slice(n).map(ss => this.parse(ss)),\n          ]\n        } else if (isDrive) {\n          return [\n            this.#norm(s[0]!),\n            ...s.slice(1).map(ss => this.parse(ss)),\n          ]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1,\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          (isDrive(p[3]) || isLongUNC(this.globParts[i][3]))\n        ) {\n          if (isLongUNC(this.globParts[i][3])) p[3] = 'UNC'\n          p[2] = '?'\n        }\n      }\n    }\n\n    // with noext, `@(...)` would be literal\n    if (!options.noext) this.mergeRows()\n\n    this.#pending = false\n    this.set.forEach((row, i) => {\n      for (let k = 0; k < row.length; k++) {\n        if (row[k] === PENDING) {\n          row[k] = this.parse(this.globParts[i]![k]!) as Matcher\n        }\n      }\n    })\n  }\n\n  // Merge rows that only differ in one portion, where each of them\n  // is a Matcher, into one row that matches any of them with\n  // `@(a|b|...)`. Then a path is only walked once for all of them,\n  // for example with `**/*.{js,ts}`.\n  mergeRows() {\n    let merged = true\n    while (merged) {\n      merged = false\n      const len = Math.max(0, ...this.set.map(r => r.length))\n      for (let k = 0; k < len; k++) {\n        // the rows that are the same other than at portion k\n        const groups = new Map()\n        this.set.forEach((row, i) => {\n          if (\n            !(row[k] instanceof Matcher || row[k] === PENDING) ||\n            !extSafe(this.globParts[i]![k]!)\n          ) {\n            return\n          }\n          const parts = [...this.globParts[i]!]\n          parts[k] = ''\n          const key = `${row.length}/${parts.join('/')}`\n          const g = groups.get(key)\n          if (g) g.push(i)\n          else groups.set(key, [i])\n        })\n        const drop = new Set()\n        for (const g of groups.values()) {\n          if (g.length < 2) continue\n          const [first, ...rest] = g as [number, ...number[]]\n          const alts = g.map(i => this.globParts[i]![k]!)\n          const glob = `@(${alts.join('|')})`\n          this.globParts[first]![k] = glob\n          this.set[first]![k] = this.parse(glob) as Matcher\n          for (const i of rest) drop.add(i)\n        }\n        if (drop.size) {\n          merged = true\n          this.set = this.set.filter((_, i) => !drop.has(i))\n          this.globParts = this.globParts.filter((_, i) => !drop.has(i))\n        }\n      }\n    }\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn ** into *\n    if (this.options.noglobstar) {\n      for (const partset of globParts) {\n        for (let j = 0; j < partset.length; j++) {\n          if (partset[j] === '**') {\n            partset[j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      // .. can not remove the root of a Windows path\n      const root = this.#rootIndex(parts) + 1\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (\n            set.length > root &&\n            prev &&\n            prev !== '..' &&\n            prev !== '.' &&\n            prev !== '**'\n          ) {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  // Check the path against each row before it is split. 'no' if no\n  // row can match, so it does not need to be split. 'yes' if a row of\n  // `**` and one more portion matches. 'maybe' if it must be split to\n  // know. None of this applies with partial, where the path can end\n  // before the row does.\n  //\n  // On Windows, `\\` is a separator in the path too, and the portions of\n  // a row up to its drive letter or UNC share are not checked (see\n  // #rootIndex).\n  //\n  // Each string portion of a row must be a portion of the path, so the\n  // path must contain it. Level 2 can only take portions out of the\n  // path, so this is still true then.\n  //\n  // The last portion of a row must match the last portion of the path,\n  // or the one before a trailing `/` (as a/* and a/**/* match a/b/).\n  // This does not apply to rows that end in **, rows that end in a\n  // root, or preserveMultipleSlashes (which can leave more\n  // than one '' at the end). At level 2, it does not apply if that\n  // portion is `.` or `..`, which can be\n  // resolved away. Level 2 only takes other portions out of the\n  // middle of the path.\n  //\n  // A row of `**/x` then matches if the ** can walk the portions\n  // before the one that x matches, the same as #matchGlobstar. At\n  // level 2, this is only known if none of them are `.` or `..`, so\n  // that the path does not change when it is resolved.\n  #canMatch(f: string): 'no' | 'yes' | 'maybe' {\n    const sep: PathSeps =\n      !this.isWindows || !f.includes('\\\\') ? '/'\n      : f.includes('/') ? 'both'\n      : '\\\\'\n    // the portions that f.split(/\\/+/) would end with, and where they\n    // start in f, found when a row needs them. `ends` is 0 until they\n    // are found, then 1, or -1 if they can not be used.\n    let ends = this.#endCheck ? 0 : -1\n    let last = ''\n    let lastStart = 0\n    let prev: string | undefined\n    let prevStart = 0\n    const dot = !!this.options.dot\n    // A string compare is cheaper than includes(), and a Matcher test\n    // costs more, so the cheaper check goes first.\n    ROWS: for (let r = 0; r < this.set.length; r++) {\n      const row = this.set[r]!\n      const p = row[row.length - 1]\n      let end = ends !== -1 && this.#endRows[r]! && p !== GLOBSTAR\n      if (end && ends === 0) {\n        const i = lastSep(f, f.length, sep)\n        lastStart = i + 1\n        last = f.slice(lastStart)\n        if (last === '' && i >= 0) {\n          let j = i\n          while (j > 0 && isSep(f.charCodeAt(j - 1), sep)) j--\n          prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep) + 1\n          prev = f.slice(prevStart, j)\n        }\n        const resolves =\n          this.#level2 &&\n          (isDots(last) ||\n            (last === '' && prev !== undefined && isDots(prev)))\n        ends = resolves ? -1 : 1\n        end = !resolves\n      }\n      let tailStart = -1\n      if (end && typeof p === 'string') {\n        tailStart = endIndex(p, last, lastStart, prev, prevStart)\n        if (tailStart === -1) continue\n      }\n      if (this.#literalCheck) {\n        for (const l of this.#literals[r]!) {\n          if (!f.includes(l)) continue ROWS\n        }\n      }\n      if (end && typeof p === 'object') {\n        tailStart = endIndex(p, last, lastStart, prev, prevStart)\n        if (tailStart === -1) continue\n      }\n      const shape = this.#shapes[r]\n      if (shape === 'base' && end) return 'yes'\n      if (shape === 'tail' && end) {\n        if (this.#level2 && dotPortion(f, 0, tailStart, true, sep)) {\n          return 'maybe'\n        }\n        if (!dotPortion(f, 0, tailStart, dot, sep)) return 'yes'\n        continue\n      }\n      if (shape === 'mid' || shape === 'head') {\n        const m = this.#walk(f, row, shape === 'head', dot, sep)\n        if (m !== 'no') return m\n        continue\n      }\n      return 'maybe'\n    }\n    return 'no'\n  }\n\n  // Match a row of a known shape against the split path, the same as\n  // #matchGlobstar and #matchGlobStarBodySections do. None of these\n  // rows have a drive letter, so they start at the first portion.\n  #matchShape(\n    file: string[],\n    row: ParseReturnFiltered[],\n    shape: 'tail' | 'mid' | 'head',\n  ): boolean {\n    const dot = !!this.options.dot\n    const n = file.length\n    if (shape === 'head') {\n      // x, then at least one portion that ** can walk\n      if (n < 2 || !portionMatch(row[0] as string | Matcher, file[0]!)) {\n        return false\n      }\n      for (let i = 1; i < n; i++)\n        if (!walkable(file[i]!, dot)) return false\n      return true\n    }\n    const x = row[1] as string | Matcher\n    if (shape === 'tail') {\n      // x is the last portion, or the one before a trailing ''\n      let t = n - 1\n      if (!portionMatch(x, file[t]!)) {\n        if (file[t] !== '' || n === 1 || !portionMatch(x, file[--t]!)) {\n          return false\n        }\n      }\n      for (let i = 0; i < t; i++)\n        if (!walkable(file[i]!, dot)) return false\n      return true\n    }\n    // mid: the first x that ** can walk to, with a portion after it,\n    // and ** can walk all of those\n    for (let k = 0; k < n; k++) {\n      if (portionMatch(x, file[k]!) && k + 1 < n) {\n        let i = k + 1\n        while (i < n && walkable(file[i]!, dot)) i++\n        if (i === n) return true\n      }\n      if (!walkable(file[k]!, dot)) return false\n    }\n    return false\n  }\n\n  // Match a row of `**/x/**` or `x/**` against the path, the same as\n  // #matchGlobstar and #matchGlobStarBodySections do once it is split.\n  // x must match a portion (the first one, for `x/**`), the ** before\n  // it must be able to walk the portions before that one, and there\n  // must be a portion after it, which the ** after it can walk. At\n  // level 2, this is only known if no portion is `.` or `..`.\n  #walk(\n    f: string,\n    row: ParseReturnFiltered[],\n    head: boolean,\n    dot: boolean,\n    sep: PathSeps,\n  ): 'yes' | 'no' | 'maybe' {\n    if (this.#level2 && dotPortion(f, 0, f.length, true, sep))\n      return 'maybe'\n    const x = row[head ? 0 : 1] as string | Matcher\n    // the last portion has none after it, so it can not be x\n    let s = 0\n    for (let e = nextSep(f, s, sep); e !== -1; e = nextSep(f, s, sep)) {\n      // the start of the next portion\n      let next = e + 1\n      while (next < f.length && isSep(f.charCodeAt(next), sep)) next++\n      const hit =\n        typeof x === 'string' ?\n          e - s === x.length && f.startsWith(x, s)\n        : e > s && x.testUnchecked(f.slice(s, e))\n      if (hit && !dotPortion(f, next, f.length, dot, sep)) return 'yes'\n      if (head || dotPortion(f, s, next, dot, sep)) return 'no'\n      s = next\n    }\n    return 'no'\n  }\n\n  // the last split, if it was the same path with the same split\n  // settings\n  #cachedSplit(f: string) {\n    const last = lastSplit\n    return (\n        last?.f === f &&\n          last.isWindows === this.isWindows &&\n          last.preserveMultipleSlashes === this.preserveMultipleSlashes &&\n          last.normalize === this.#form\n      ) ?\n        last\n      : undefined\n  }\n\n  // split a path for match(), and keep the parts for the next call\n  #split(f: string) {\n    const { isWindows, preserveMultipleSlashes } = this\n    // windows: need to use /, not \\\n    let parts = this.#slashSplit(isWindows ? f.split('\\\\').join('/') : f)\n    // normalize each portion, so that a char that normalizes to `/`\n    // does not make a new portion\n    const normalize = this.#form\n    if (normalize) parts = parts.map(p => p.normalize(normalize))\n    lastSplit = {\n      f,\n      isWindows,\n      preserveMultipleSlashes,\n      normalize,\n      parts,\n    }\n    return lastSplit\n  }\n\n  // resolve `.` and `..` portions of a path, for level 2\n  #levelTwoFileOptimize(file: string[]) {\n    // work on a copy, so that the cached parts do not change\n    const parts = [...file]\n    let didSomething: boolean = false\n\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      // .. can not remove the root of a Windows path\n      const root = this.#rootIndex(parts) + 1\n      let dd: number = root\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd = Math.max(dd - 2, root)\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    // each **/.. split doubles the patterns, and adds a copy of the\n    // whole pattern. Throw if either gets too large. A partial split\n    // would match some paths and not others, depending on which rows\n    // the pass reached first.\n    const { braceExpandMax = 100_000 } = this.options\n    let splitCells = 0\n    const maxSplitCells = 1_000_000\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          // Check before changing parts or allocating the new row.\n          const addedCells = parts.length - 1\n          if (\n            globParts.length >= braceExpandMax ||\n            splitCells + addedCells > maxSplitCells\n          ) {\n            throw new RangeError(\n              `optimizationLevel 2: too many patterns from '**/..'`,\n            )\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          splitCells += addedCells\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        // .. can not remove the root of a Windows path\n        const root = this.#rootIndex(parts) + 1\n        let dd: number = root\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd = Math.max(dd - 2, root)\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/,
/} -> 
/\n  // {
/*/,
/

/} ->

/*/\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    const keys = new Set()\n    const rows = globParts.filter(parts => {\n      const key = parts.join('/')\n      if (keys.has(key)) return false\n      keys.add(key)\n      return true\n    })\n\n    // A row is covered by another row that has `*` at some positions,\n    // and is the same at all others. Collect each distinct set of `*`\n    // positions, then look up each row with `*` put at those positions.\n    const stars = new Map()\n    for (const parts of rows) {\n      const s: number[] = []\n      for (let i = 0; i < parts.length; i++) {\n        if (parts[i] === '*') s.push(i)\n      }\n      if (s.length) stars.set(s.join(','), s)\n    }\n    // Each row is checked against each set of `*` positions, so skip\n    // this if there are too many. The patterns match the same paths\n    // either way.\n    if (!stars.size || rows.length * stars.size > 100_000) return rows\n\n    const { dot } = this.options\n    return rows.filter(parts => {\n      for (const s of stars.values()) {\n        if (s[s.length - 1]! >= parts.length) continue\n        const c = [...parts]\n        let ok = true\n        let changed = false\n        for (const i of s) {\n          const p = parts[i]!\n          if (p === '*') continue\n          if (!p || p === '**' || (!dot && p.startsWith('.'))) {\n            ok = false\n            break\n          }\n          c[i] = '*'\n          changed = true\n        }\n        if (ok && changed && keys.has(c.join('/'))) return false\n      }\n      return true\n    })\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // Match the parts of a path against one row of the set. `resolved`\n  // is the parts after level 2 resolves `.` and `..` in them, or the\n  // same parts below level 2. Set partial to true to test if, for\n  // example, \"/a/b\" matches the start of \"/*/b/*/d\". Partial means, if\n  // you run out of file before you run out of pattern, then that's\n  // fine, as long as all the parts match.\n  #matchRow(\n    file: string[],\n    resolved: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n  ) {\n    let fileStartIndex = 0\n    let patternStartIndex = 0\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa, and\n    // //?/UNC/host/share/... can match //host/share/... and vice versa.\n    // Drive letters in absolute drive or unc paths, and the host and\n    // share of UNC paths, are always compared case-insensitively.\n    const fh = this.isWindows ? uncHost(resolved) : -1\n    const ph = fh === -1 ? -1 : uncHost(pattern)\n    if (ph !== -1) {\n      const host = pattern[ph]\n      const share = pattern[ph + 1]\n      if (typeof host !== 'string' || typeof share !== 'string') {\n        // a host or share with magic is matched as usual\n        fileStartIndex = fh\n        patternStartIndex = ph\n      } else if (\n        resolved[fh]!.toLowerCase() === host.toLowerCase() &&\n        resolved[fh + 1]!.toLowerCase() === share.toLowerCase()\n      ) {\n        fileStartIndex = fh + 2\n        patternStartIndex = ph + 2\n      }\n    } else if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi =\n        fileUNC ? 3\n        : fileDrive ? 0\n        : undefined\n      const pdi =\n        patternUNC ? 3\n        : patternDrive ? 0\n        : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        // the drives match, so start matching after them\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          patternStartIndex = pdi + 1\n          fileStartIndex = fdi + 1\n        }\n      }\n    }\n\n    // the drive letters are found in the parts before level 2 resolves\n    // them, and the match uses the resolved parts\n    file = resolved\n\n    if (pattern.includes(GLOBSTAR)) {\n      return this.#matchGlobstar(\n        file,\n        pattern,\n        partial,\n        fileStartIndex,\n        patternStartIndex,\n      )\n    }\n\n    return this.#matchOne(\n      file,\n      pattern,\n      partial,\n      fileStartIndex,\n      patternStartIndex,\n    )\n  }\n\n  #matchGlobstar(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n  ) {\n    const { head, body, tail, segments } = this.#getGlobstarParts(\n      pattern,\n      partial,\n      patternIndex,\n    )\n\n    // check the head, from the current file/pattern index.\n    if (head.length) {\n      const headEnd = fileIndex + head.length\n      if (!this.#matchOne(file, head, partial, fileIndex, 0, headEnd)) {\n        return false\n      }\n      fileIndex += head.length\n      patternIndex += head.length\n    }\n    // now we know the head matches!\n\n    // if the last portion is not empty, it MUST match the end\n    // check the tail\n    let fileTailMatch: number = 0\n    if (tail.length) {\n      // if head + tail > file, then we cannot possibly match\n      if (tail.length + fileIndex > file.length) return false\n\n      // try to match the tail\n      let tailStart = file.length - tail.length\n      if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n        fileTailMatch = tail.length\n      } else {\n        // affordance for stuff like a/**/* matching a/b/\n        // if the last file portion is '', and there's more to the pattern\n        // then try without the '' bit.\n        if (\n          file[file.length - 1] !== '' ||\n          fileIndex + tail.length === file.length\n        ) {\n          return false\n        }\n        tailStart--\n        if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n          return false\n        }\n        fileTailMatch = tail.length + 1\n      }\n    }\n\n    // now we know the tail matches!\n\n    // the middle is zero or more portions wrapped in **, possibly\n    // containing more ** sections.\n    // so a/**/b/**/c/**/d has become **/b/**/c/**\n    // if it's empty, it means a/**/b, just verify we have no bad dots\n    // if there's no tail, so it ends on /**, then we must have *something*\n    // after the head, or it's not a matc\n    if (!body.length) {\n      let sawSome = !!fileTailMatch\n      for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n        const f = String(file[i])\n        sawSome = true\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      // in partial mode, we just need to get past all file parts\n      return partial || sawSome\n    }\n\n    // now we know that there's one or more body sections, which can\n    // be matched anywhere from the 0 index (because the head was pruned)\n    // through to the length-fileTailMatch index.\n    return !!this.#matchGlobStarBodySections(\n      file,\n      segments,\n      file.length - fileTailMatch,\n      fileIndex,\n      0,\n      partial,\n      0,\n      !!fileTailMatch,\n      new Set(),\n    )\n  }\n\n  // Split the pattern into head, tail, and middle of ** delimited\n  // parts. The tail has to be at the end, and the others just have to\n  // be found in order from the head. These only depend on the pattern\n  // row, so they are kept for the next path.\n  #getGlobstarParts(\n    pattern: ParseReturn[],\n    partial: boolean,\n    patternIndex: number,\n  ): GlobstarParts {\n    let byStart = this.#globstarParts.get(pattern)\n    if (!byStart) {\n      byStart = []\n      this.#globstarParts.set(pattern, byStart)\n    }\n    const key = patternIndex * 2 + (partial ? 1 : 0)\n    const found = byStart[key]\n    if (found) return found\n\n    const firstgs = pattern.indexOf(GLOBSTAR, patternIndex)\n    const lastgs = pattern.lastIndexOf(GLOBSTAR)\n    const head = pattern.slice(patternIndex, firstgs)\n    const body = pattern.slice(firstgs + 1, partial ? undefined : lastgs)\n    const tail = partial ? [] : pattern.slice(lastgs + 1)\n\n    // split the body up into sections, and note the number of\n    // portions that must come after the start of each one\n    const segments: [ParseReturn[], number][] = [[[], 0]]\n    let current = segments[0]!\n    let nonGsParts = 0\n    const nonGsPartsSums: number[] = [0]\n    for (const b of body) {\n      if (b === GLOBSTAR) {\n        nonGsPartsSums.push(nonGsParts)\n        current = [[], 0]\n        segments.push(current)\n      } else {\n        current[0].push(b)\n        nonGsParts++\n      }\n    }\n    // the portions in this section and the ones after it\n    segments.forEach((b, i) => {\n      b[1] = nonGsParts - (nonGsPartsSums[i] as number)\n    })\n\n    const parts = { head, body, tail, segments }\n    byStart[key] = parts\n    return parts\n  }\n\n  // return false for \"nope, not matching\"\n  // return null for \"not matching, cannot keep trying\"\n  #matchGlobStarBodySections(\n    file: string[],\n    // pattern section, and the portions that it and the rest need\n    bodySegments: [ParseReturn[], number][],\n    // the end of the file portions that the body can match\n    fileLength: number,\n    fileIndex: number,\n    bodyIndex: number,\n    partial: boolean,\n    globStarDepth: number,\n    sawTail: boolean,\n    // the places that a walk has already tried, as\n    // bodyIndex * (file.length + 1) + fileIndex. A walk from a place\n    // does the same no matter how it got there, and it only comes back\n    // if it found no match, so a walk that gets to one stops.\n    tried: Set,\n  ): boolean | null {\n    // take the first body segment, and walk from fileIndex to its \"after\"\n    // value at the end\n    // If it doesn't match at that position, we increment, until we hit\n    // that final possible position, and give up.\n    // If it does match, then advance and try to rest.\n    // If any of them fail we keep walking forward.\n    // this is still a bit recursively painful, but it's more constrained\n    // than previous implementations, because we never test something that\n    // can't possibly be a valid matching condition.\n    const bs = bodySegments[bodyIndex]\n    if (!bs) {\n      // with partial, the body is the rest of the pattern, so it\n      // matches if no portions are left, or only the '' of a trailing\n      // / (as a/* matches a/b/). A ** at the end walks them as its own\n      // empty section.\n      if (partial) {\n        return (\n          fileIndex >= fileLength ||\n          (fileIndex === fileLength - 1 && file[fileIndex] === '')\n        )\n      }\n      // just make sure that there's no bad dots before the tail\n      for (let i = fileIndex; i < fileLength; i++) {\n        sawTail = true\n        const f = file[i]\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      return sawTail\n    }\n\n    // have a non-globstar body section to test, up to the last index\n    // where it can start\n    const [body, need] = bs\n    // with partial, the path can end before the body does\n    const after = partial ? fileLength : fileLength - need\n    while (fileIndex <= after) {\n      const key = bodyIndex * (file.length + 1) + fileIndex\n      if (tried.has(key)) return false\n      tried.add(key)\n      const m = this.#matchOne(\n        file,\n        body,\n        partial,\n        fileIndex,\n        0,\n        fileIndex + body.length,\n      )\n      // if limit exceeded, no match. intentional false negative,\n      // acceptable break in correctness for security.\n      if (m && globStarDepth < this.maxGlobstarRecursion) {\n        // match! see if the rest match. if so, we're done!\n        const sub = this.#matchGlobStarBodySections(\n          file,\n          bodySegments,\n          fileLength,\n          fileIndex + body.length,\n          bodyIndex + 1,\n          partial,\n          globStarDepth + 1,\n          sawTail,\n          tried,\n        )\n        if (sub !== false) {\n          return sub\n        }\n      }\n      // the ** does not walk past the last place the body can start\n      if (fileIndex === after) break\n      const f = file[fileIndex]!\n      if (\n        f === '.' ||\n        f === '..' ||\n        (!this.options.dot && f.startsWith('.'))\n      ) {\n        return false\n      }\n\n      fileIndex++\n    }\n    // walked off. no point continuing\n    return partial || null\n  }\n\n  #matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n    // only match the file portions before this index\n    fileEnd: number = file.length,\n  ) {\n    let fi: number\n    let pi: number\n    let pl: number\n    let fl: number\n    for (\n      fi = fileIndex,\n        pi = patternIndex,\n        fl = Math.min(fileEnd, file.length),\n        pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      let p = pattern[pi]\n      let f = file[fi]\n\n      // should be impossible.\n      /* c8 ignore start */\n      if (p === false || p === GLOBSTAR) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into Matchers.\n      if (!portionMatch(p, f)) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though * can match \"\", except in\n    // partial mode, where it might simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  // Expand braces, except numeric ranges such as {0..999} with at\n  // least RANGE_MIN values. Each of those stays in its pattern as\n  // `0..999`, for the Matcher to test. If a range might\n  // be inside a [...] class, expand all of them instead.\n  #expandBraces(): string[] {\n    const { pattern } = this\n    if (this.options.nobrace) return this.braceExpand()\n    let code = 0xe000\n    while (pattern.includes(String.fromCharCode(code))) {\n      if (++code > 0xf8ff) return this.braceExpand()\n    }\n    const mark = String.fromCharCode(code)\n    let found = false\n    const marked = pattern.replace(\n      rangeRe,\n      (m, lo: string, hi: string) => {\n        const a = Number(lo)\n        const b = Number(hi)\n        if (\n          !Number.isSafeInteger(a) ||\n          !Number.isSafeInteger(b) ||\n          Math.abs(a - b) + 1 < RANGE_MIN\n        ) {\n          return m\n        }\n        found = true\n        return `${mark}${lo}..${hi}${mark}`\n      },\n    )\n    if (!found) return this.braceExpand()\n    const set = braceExpand(marked, this.options)\n    for (const p of set) {\n      for (const portion of p.split('/')) {\n        const c = portion.indexOf('[')\n        if (c !== -1 && c < portion.lastIndexOf(mark)) {\n          return this.braceExpand()\n        }\n      }\n    }\n    this.#rangeMark = mark\n    return set\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    const {\n      nocase,\n      nocaseMagicOnly,\n      noext = false,\n      dot,\n      normalize,\n    } = options\n    const rangeMark = this.#rangeMark\n    const lit =\n      rangeMark && pattern.includes(rangeMark) ?\n        undefined\n      : literal(pattern, noext)\n    // in nocase mode, a literal with cased chars still needs a\n    // Matcher, unless nocaseMagicOnly is set.\n    if (\n      lit !== undefined &&\n      !(\n        nocase &&\n        !nocaseMagicOnly &&\n        pattern.toUpperCase() !== pattern.toLowerCase()\n      )\n    ) {\n      return this.#norm(lit)\n    }\n\n    if (this.#pending) return PENDING\n    let m = this.#matchers.get(pattern)\n    if (!m) {\n      m = new Matcher(pattern, {\n        nocase,\n        noext,\n        dot,\n        normalize,\n        ...(rangeMark && { rangeMark }),\n      })\n      this.#matchers.set(pattern, m)\n    }\n    return m\n  }\n\n  #slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // treat the test path as a set of pathparts. If it was not just\n    // split or checked, check that it can match before splitting it.\n    let split = this.#cachedSplit(f)\n    if (!split) {\n      // the checks look at the path as given, so not if it is\n      // normalized\n      if (\n        !partial &&\n        !this.#form &&\n        (this.#endCheck || this.#literalCheck) &&\n        lastChecked !== f\n      ) {\n        lastChecked = f\n        const can = this.#canMatch(f)\n        if (can === 'no') return options.flipNegate ? false : this.negate\n        if (can === 'yes') return options.flipNegate ? true : !this.negate\n      }\n      split = this.#split(f)\n    }\n    const ff = split.parts\n    // the parts after level 2 resolves them, kept for the next pattern\n    // that tests the same path\n    const resolved =\n      this.#level2 ?\n        (split.resolved ??= this.#levelTwoFileOptimize(ff))\n      : ff\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let r = 0; r < set.length; r++) {\n      const pattern = set[r]!\n      const shape = partial ? undefined : this.#shapes[r]\n      // level 2 does not change a path of one portion\n      const hit =\n        shape === 'base' ?\n          portionMatch(pattern[0] as string | Matcher, filename)\n        : shape ? this.#matchShape(resolved, pattern, shape)\n        : options.matchBase && pattern.length === 1 ?\n          this.#matchRow([filename], [filename], pattern, partial)\n        : this.#matchRow(ff, resolved, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\nexport type { Form }\n/* c8 ignore stop */\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n", "// simple node version that imports from node builtin\n// this is built to both ESM and CommonJS on the 'node' import path\nimport { tracingChannel, channel } from 'node:diagnostics_channel'\nimport type { TracingChannel, Channel } from 'node:diagnostics_channel'\nexport type { TracingChannel, Channel }\nexport const metrics: Channel = channel('lru-cache:metrics')\nexport const tracing: TracingChannel = tracingChannel('lru-cache')\n", "/**\n * this provides the default Perf object source, either the\n * `performance` global, or the `Date` constructor.\n *\n * it can be passed in via configuration to override it\n * for a single LRU object.\n */\nexport type Perf = { now: () => number }\nexport const defaultPerf: Perf =\n  (\n    typeof performance === 'object' &&\n    performance &&\n    typeof performance.now === 'function'\n  ) ?\n    /* c8 ignore start - this gets covered, but c8 gets confused */\n    performance\n  : /* c8 ignore stop */ Date\n", "/**\n * @module LRUCache\n */\n\nimport { metrics, tracing } from './diagnostics-channel.js'\nimport { defaultPerf } from './perf.js'\nimport type { Perf } from './perf.js'\nexport type { Perf } from './perf.js'\n\nconst hasSubscribers = () =>\n  metrics.hasSubscribers || tracing.hasSubscribers\n\nconst warned = new Set()\n\n// either a function or a class\n// oxlint-disable-next-line no-explicit-any\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n  typeof process === 'object' && !!process ?\n    process\n  : {}) as { [k: string]: unknown }\n/* c8 ignore stop */\n\nconst emitWarning = (\n  msg: string,\n  type: string,\n  code: string,\n  fn: ForC,\n) => {\n  if (typeof PROCESS.emitWarning === 'function') {\n    PROCESS.emitWarning(msg, type, code, fn)\n  } else {\n    //oxlint-disable-next-line no-console\n    console.error(`[${code}] ${type}: ${msg}`)\n  }\n}\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: unknown): n is PosInt =>\n  !!n && n === Math.floor(n as number) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values.  Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\n/* c8 ignore start */\nconst getUintArray = (max: number) =>\n  !isPosInt(max) ? null\n  : max <= Math.pow(2, 8) ? Uint8Array\n  : max <= Math.pow(2, 16) ? Uint16Array\n  : max <= Math.pow(2, 32) ? Uint32Array\n  : max <= Number.MAX_SAFE_INTEGER ? ZeroArray\n  : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array {\n  constructor(size: number) {\n    super(size)\n    this.fill(0)\n  }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n  /* c8 ignore start - not sure why this is showing up uncovered?? */\n  heap: NumberArray\n  /* c8 ignore stop */\n  length: number\n  // private constructor\n  static #constructing: boolean = false\n  static create(max: number): StackLike {\n    const HeapCls = getUintArray(max)\n    if (!HeapCls) return []\n    Stack.#constructing = true\n    const s = new Stack(max, HeapCls)\n    Stack.#constructing = false\n    return s\n  }\n  constructor(max: number, HeapCls: { new (n: number): NumberArray }) {\n    /* c8 ignore start */\n    if (!Stack.#constructing) {\n      throw new TypeError('instantiate Stack using Stack.create(n)')\n    }\n    /* c8 ignore stop */\n    this.heap = new HeapCls(max)\n    this.length = 0\n  }\n  push(n: Index) {\n    this.heap[this.length++] = n\n  }\n  pop(): Index {\n    return this.heap[--this.length] as Index\n  }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch = Promise & {\n  __returned: BackgroundFetch | undefined\n  __abortController: AbortController\n  __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask = [\n  value: V,\n  key: K,\n  reason: LRUCache.DisposeReason,\n]\n\nexport namespace LRUCache {\n  /**\n   * An integer greater than 0, reflecting the calculated size of items\n   */\n  export type Size = number\n\n  /**\n   * Integer greater than 0, representing some number of milliseconds, or the\n   * time at which a TTL started counting from.\n   */\n  export type Milliseconds = number\n\n  /**\n   * An integer greater than 0, reflecting a number of items\n   */\n  export type Count = number\n\n  /**\n   * The reason why an item was removed from the cache, passed\n   * to the {@link Disposer} methods.\n   *\n   * - `evict`: The item was evicted because it is the least recently used,\n   *   and the cache is full.\n   * - `set`: A new value was set, overwriting the old value being disposed.\n   * - `delete`: The item was explicitly deleted, either by calling\n   *   {@link LRUCache#delete}, {@link LRUCache#clear}, or\n   *   {@link LRUCache#set} with an undefined value.\n   * - `expire`: The item was removed due to exceeding its TTL.\n   * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n   *   `undefined` or was aborted, causing the item to be deleted.\n   */\n  export type DisposeReason =\n    | 'evict'\n    | 'set'\n    | 'delete'\n    | 'expire'\n    | 'fetch'\n  /**\n   * A method called upon item removal, passed as the\n   * {@link OptionsBase.dispose} and/or\n   * {@link OptionsBase.disposeAfter} options.\n   */\n  export type Disposer = (\n    value: V,\n    key: K,\n    reason: DisposeReason,\n  ) => void\n\n  /**\n   * The reason why an item was added to the cache, passed\n   * to the {@link Inserter} methods.\n   *\n   * - `add`: the item was not found in the cache, and was added\n   * - `update`: the item was in the cache, with the same value provided\n   * - `replace`: the item was in the cache, and replaced\n   */\n  export type InsertReason = 'add' | 'update' | 'replace'\n\n  /**\n   * A method called upon item insertion, passed as the\n   * {@link OptionsBase.insert}\n   */\n  export type Inserter = (\n    value: V,\n    key: K,\n    reason: InsertReason,\n  ) => void\n\n  /**\n   * A function that returns the effective calculated size\n   * of an entry in the cache.\n   */\n  export type SizeCalculator = (value: V, key: K) => Size\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.fetchMethod} function.\n   */\n  export interface FetcherOptions {\n    signal: AbortSignal\n    options: FetcherFetchOptions\n    /**\n     * Object provided in the {@link FetchOptions.context} option to\n     * {@link LRUCache#fetch}\n     */\n    context: FC\n  }\n\n  /**\n   * Occasionally, it may be useful to track the internal behavior of the\n   * cache, particularly for logging, debugging, or for behavior within the\n   * `fetchMethod`. To do this, you can pass a `status` object to the\n   * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n   * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n   *\n   * The `status` option should be a plain JavaScript object. The following\n   * fields will be set on it appropriately, depending on the situation.\n   *\n   * These objects are also the context objects passed to listeners on the\n   * `lru-cache:metrics` diagnostic channel, and the `lru-cache` tracing\n   * channels, in platforms that support them.\n   */\n  export interface Status {\n    /**\n     * The operation being performed\n     */\n    op?: 'get' | 'set' | 'memo' | 'fetch' | 'delete' | 'has' | 'peek'\n    /**\n     * The status of a set() operation.\n     *\n     * - add: the item was not found in the cache, and was added\n     * - update: the item was in the cache, with the same value provided\n     * - replace: the item was in the cache, and replaced\n     * - miss: the item was not added to the cache for some reason\n     */\n    set?: 'add' | 'update' | 'replace' | 'miss' | 'deleted'\n\n    /**\n     * The status of a delete() operation.\n     */\n    delete?: LRUCache.DisposeReason\n\n    /**\n     * The result of a peek() operation\n     *\n     * - hit: the item was found and returned\n     * - stale: the item is in the cache, but past its ttl and not returned\n     * - miss: item not in the cache\n     */\n    peek?: 'hit' | 'miss' | 'stale'\n\n    /**\n     * The status of a memo() operation.\n     *\n     * - 'hit': the item was found in the cache and returned\n     * - 'miss': the `memoMethod` function was called\n     */\n    memo?: 'hit' | 'miss'\n\n    /**\n     * The `context` option provided to a memo or fetch operation\n     *\n     * In practice, of course, this will be the same type as the `FC`\n     * fetch context param used to instantiate the LRUCache, but the\n     * convolutions of threading that through would get quite complicated,\n     * and preclude forcing/forbidding the passing of a `context` param\n     * where it is/isn't expected, which is more valuable for error\n     * prevention.\n     */\n    context?: unknown\n\n    /**\n     * the ttl stored for the item, or undefined if ttls are not used.\n     */\n    ttl?: Milliseconds\n\n    /**\n     * the start time for the item, or undefined if ttls are not used.\n     */\n    start?: Milliseconds\n\n    /**\n     * The timestamp used for TTL calculation\n     */\n    now?: Milliseconds\n\n    /**\n     * the remaining ttl for the item, or undefined if ttls are not used.\n     */\n    remainingTTL?: Milliseconds\n\n    /**\n     * The calculated size for the item, if sizes are used.\n     */\n    entrySize?: Size\n\n    /**\n     * The total calculated size of the cache, if sizes are used.\n     */\n    totalCalculatedSize?: Size\n\n    /**\n     * A flag indicating that the item was not stored, due to exceeding the\n     * {@link OptionsBase.maxEntrySize}\n     */\n    maxEntrySizeExceeded?: true\n\n    /**\n     * The key that was set or retrieved\n     */\n    key?: K\n\n    /**\n     * The value that was set\n     */\n    value?: V\n\n    /**\n     * The old value, specified in the case of `set:'replace'`\n     */\n    oldValue?: V\n\n    /**\n     * The results of a {@link LRUCache#has} operation\n     *\n     * - hit: the item was found in the cache\n     * - stale: the item was found in the cache, but is stale\n     * - miss: the item was not found in the cache\n     */\n    has?: 'hit' | 'stale' | 'miss'\n\n    /**\n     * The status of a {@link LRUCache#fetch} operation.\n     * Note that this can change as the underlying fetch() moves through\n     * various states.\n     *\n     * - inflight: there is another fetch() for this key which is in process\n     * - get: there is no {@link OptionsBase.fetchMethod}, so\n     *   {@link LRUCache#get} was called.\n     * - miss: the item is not in cache, and will be fetched.\n     * - hit: the item is in the cache, and was resolved immediately.\n     * - stale: the item is in the cache, but stale.\n     * - refresh: the item is in the cache, and not stale, but\n     *   {@link FetchOptions.forceRefresh} was specified.\n     */\n    fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n    /**\n     * `forceRefresh` option was used for either a fetch or memo operation\n     */\n    forceRefresh?: boolean\n\n    /**\n     * The {@link OptionsBase.fetchMethod} was called\n     */\n    fetchDispatched?: true\n\n    /**\n     * The cached value was updated after a successful call to\n     * {@link OptionsBase.fetchMethod}\n     */\n    fetchUpdated?: true\n\n    /**\n     * The reason for a fetch() rejection.  Either the error raised by the\n     * {@link OptionsBase.fetchMethod}, or the reason for an\n     * AbortSignal.\n     */\n    fetchError?: Error\n\n    /**\n     * The fetch received an abort signal\n     */\n    fetchAborted?: true\n\n    /**\n     * The abort signal received was ignored, and the fetch was allowed to\n     * continue in the background.\n     */\n    fetchAbortIgnored?: true\n\n    /**\n     * The fetchMethod promise resolved successfully\n     */\n    fetchResolved?: true\n\n    /**\n     * The fetchMethod promise was rejected\n     */\n    fetchRejected?: true\n\n    /**\n     * The status of a {@link LRUCache#get} operation.\n     *\n     * - fetching: The item is currently being fetched.  If a previous value\n     *   is present and allowed, that will be returned.\n     * - stale: The item is in the cache, and is stale. If it was returned,\n     *   then the `returnedStale` flag will be set.\n     * - stale-fetching: The value is being fetched in the background, but is\n     *   currently stale. If the stale value was returned, then the\n     *   `returnedStale` flag will be set.\n     * - hit: the item is in the cache\n     * - miss: the item is not in the cache\n     */\n    get?: 'stale' | 'hit' | 'miss' | 'fetching' | 'stale-fetching'\n\n    /**\n     * A fetch or get operation returned a stale value.\n     */\n    returnedStale?: true\n\n    /**\n     * A tracingChannel trace was started for this operation\n     */\n    trace?: boolean\n\n    /**\n     * A reference to the cache instance associated with this operation\n     */\n    cache?: LRUCache\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#fetch}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link OptionsBase.noDeleteOnFetchRejection},\n   * {@link OptionsBase.allowStaleOnFetchRejection},\n   * {@link FetchOptions.forceRefresh}, and\n   * {@link FetcherOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the fetchMethod is called.\n   */\n  export interface FetcherFetchOptions extends Pick<\n    OptionsBase,\n    | 'allowStale'\n    | 'updateAgeOnGet'\n    | 'noDeleteOnStaleGet'\n    | 'sizeCalculation'\n    | 'ttl'\n    | 'noDisposeOnSet'\n    | 'noUpdateTTL'\n    | 'noDeleteOnFetchRejection'\n    | 'allowStaleOnFetchRejection'\n    | 'ignoreFetchAbort'\n    | 'allowStaleOnFetchAbort'\n  > {\n    status?: Status\n    size?: Size\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#fetch} method.\n   */\n  export interface FetchOptions extends FetcherFetchOptions<\n    K,\n    V,\n    FC\n  > {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.fetchMethod} as\n     * the {@link FetcherOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    signal?: AbortSignal\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface FetchOptionsWithContext extends FetchOptions<\n    K,\n    V,\n    FC\n  > {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface FetchOptionsNoContext<\n    K,\n    V,\n    FC extends undefined | void = undefined,\n  > extends FetchOptions {\n    context?: FC\n  }\n\n  export interface MemoOptions extends Pick<\n    OptionsBase,\n    | 'allowStale'\n    | 'updateAgeOnGet'\n    | 'noDeleteOnStaleGet'\n    | 'sizeCalculation'\n    | 'ttl'\n    | 'noDisposeOnSet'\n    | 'noUpdateTTL'\n    | 'noDeleteOnFetchRejection'\n    | 'allowStaleOnFetchRejection'\n    | 'ignoreFetchAbort'\n    | 'allowStaleOnFetchAbort'\n  > {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.memoMethod} as\n     * the {@link MemoizerOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface MemoOptionsWithContext extends MemoOptions<\n    K,\n    V,\n    FC\n  > {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface MemoOptionsNoContext<\n    K,\n    V,\n    FC extends undefined | void = undefined,\n  > extends MemoOptions {\n    context?: FC\n  }\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.memoMethod} function.\n   */\n  export interface MemoizerOptions {\n    options: MemoizerMemoOptions\n    /**\n     * Object provided in the {@link MemoOptions.context} option to\n     * {@link LRUCache#memo}\n     */\n    context: FC\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#memo}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link MemoOptions.forceRefresh}, and\n   * {@link MemoOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.memoMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the memoMethod is called.\n   */\n  export interface MemoizerMemoOptions extends Pick<\n    OptionsBase,\n    | 'allowStale'\n    | 'updateAgeOnGet'\n    | 'noDeleteOnStaleGet'\n    | 'sizeCalculation'\n    | 'ttl'\n    | 'noDisposeOnSet'\n    | 'noUpdateTTL'\n  > {\n    status?: Status\n    size?: Size\n    start?: Milliseconds\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#has} method.\n   */\n  export interface HasOptions extends Pick<\n    OptionsBase,\n    'updateAgeOnHas'\n  > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#get} method.\n   */\n  export interface GetOptions extends Pick<\n    OptionsBase,\n    'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n  > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#peek} method.\n   */\n  export interface PeekOptions extends Pick<\n    OptionsBase,\n    'allowStale'\n  > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#set} method.\n   */\n  export interface SetOptions extends Pick<\n    OptionsBase,\n    'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n  > {\n    /**\n     * If size tracking is enabled, then setting an explicit size\n     * in the {@link LRUCache#set} call will prevent calling the\n     * {@link OptionsBase.sizeCalculation} function.\n     */\n    size?: Size\n    /**\n     * If TTL tracking is enabled, then setting an explicit start\n     * time in the {@link LRUCache#set} call will override the\n     * default time from `performance.now()` or `Date.now()`.\n     *\n     * Note that it must be a valid value for whichever time-tracking\n     * method is in use.\n     */\n    start?: Milliseconds\n    status?: Status\n  }\n\n  /**\n   * The type signature for the {@link OptionsBase.fetchMethod} option.\n   */\n  export type Fetcher = (\n    key: K,\n    staleValue: V | undefined,\n    options: FetcherOptions,\n  ) => Promise | V | undefined | void\n\n  /**\n   * the type signature for the {@link OptionsBase.memoMethod} option.\n   */\n  export type Memoizer = (\n    key: K,\n    staleValue: V | undefined,\n    options: MemoizerOptions,\n  ) => V\n\n  /**\n   * Options which may be passed to the {@link LRUCache} constructor.\n   *\n   * Most of these may be overridden in the various options that use\n   * them.\n   *\n   * Despite all being technically optional, the constructor requires that\n   * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n   * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n   *\n   * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n   * (and in fact required by the type definitions here) that the cache\n   * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n   * unbounded storage.\n   *\n   * All options are also available on the {@link LRUCache} instance, making\n   * it safe to pass an LRUCache instance as the options argumemnt to\n   * make another empty cache of the same type.\n   *\n   * Some options are marked as read-only, because changing them after\n   * instantiation is not safe. Changing any of the other options will of\n   * course only have an effect on subsequent method calls.\n   */\n  export interface OptionsBase {\n    /**\n     * The maximum number of items to store in the cache before evicting\n     * old entries. This is read-only on the {@link LRUCache} instance,\n     * and may not be overridden.\n     *\n     * If set, then storage space will be pre-allocated at construction\n     * time, and the cache will perform significantly faster.\n     *\n     * Note that significantly fewer items may be stored, if\n     * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n     * set.\n     *\n     * **It is strongly recommended to set a `max` to prevent unbounded growth\n     * of the cache.**\n     */\n    max?: Count\n\n    /**\n     * Max time in milliseconds for items to live in cache before they are\n     * considered stale.  Note that stale items are NOT preemptively removed by\n     * default, and MAY live in the cache, contributing to its LRU max, long\n     * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n     * set.\n     *\n     * If set to `0` (the default value), then that means \"do not track\n     * TTL\", not \"expire immediately\".\n     *\n     * Also, as this cache is optimized for LRU/MRU operations, some of\n     * the staleness/TTL checks will reduce performance, as they will incur\n     * overhead by deleting items.\n     *\n     * This is not primarily a TTL cache, and does not make strong TTL\n     * guarantees. There is no pre-emptive pruning of expired items, but you\n     * _may_ set a TTL on the cache, and it will treat expired items as missing\n     * when they are fetched, and delete them.\n     *\n     * Optional, but must be a non-negative integer in ms if specified.\n     *\n     * This may be overridden by passing an options object to `cache.set()`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if ttl tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n     * and `ttlAutopurge` is not set, then a warning will be emitted\n     * cautioning about the potential for unbounded memory consumption.\n     * (The TypeScript definitions will also discourage this.)\n     */\n    ttl?: Milliseconds\n\n    /**\n     * Minimum amount of time in ms in which to check for staleness.\n     * Defaults to 1, which means that the current time is checked\n     * at most once per millisecond.\n     *\n     * Set to 0 to check the current time every time staleness is tested.\n     * (This reduces performance, and is theoretically unnecessary.)\n     *\n     * Setting this to a higher value will improve performance somewhat\n     * while using ttl tracking, albeit at the expense of keeping stale\n     * items around a bit longer than their TTLs would indicate.\n     *\n     * @default 1\n     */\n    ttlResolution?: Milliseconds\n\n    /**\n     * Preemptively remove stale items from the cache.\n     *\n     * Note that this may *significantly* degrade performance, especially if\n     * the cache is storing a large number of items. It is almost always best\n     * to just leave the stale items in the cache, and let them fall out as new\n     * items are added.\n     *\n     * Note that this means that {@link OptionsBase.allowStale} is a bit\n     * pointless, as stale items will be deleted almost as soon as they\n     * expire.\n     *\n     * Use with caution!\n     */\n    ttlAutopurge?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever it is retrieved from cache with\n     * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n     * of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     */\n    updateAgeOnGet?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever its presence in the cache is\n     * checked with {@link LRUCache#has}, causing it to not expire. (It can\n     * still fall out of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     */\n    updateAgeOnHas?: boolean\n\n    /**\n     * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n     * stale data, if available.\n     *\n     * By default, if you set `ttl`, stale items will only be deleted from the\n     * cache when you `get(key)`. That is, it's not preemptively pruning items,\n     * unless {@link OptionsBase.ttlAutopurge} is set.\n     *\n     * If you set `allowStale:true`, it'll return the stale value *as well as*\n     * deleting it. If you don't set this, then it'll return `undefined` when\n     * you try to get a stale entry.\n     *\n     * Note that when a stale entry is fetched, _even if it is returned due to\n     * `allowStale` being set_, it is removed from the cache immediately. You\n     * can suppress this behavior by setting\n     * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n     * the options provided to {@link LRUCache#get}.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     * The `cache.has()` method will always return `false` for stale items.\n     *\n     * Only relevant if a ttl is set.\n     */\n    allowStale?: boolean\n\n    /**\n     * Function that is called on items when they are dropped from the\n     * cache, as `dispose(value, key, reason)`.\n     *\n     * This can be handy if you want to close file descriptors or do\n     * other cleanup tasks when items are no longer stored in the cache.\n     *\n     * **NOTE**: It is called _before_ the item has been fully removed\n     * from the cache, so if you want to put it right back in, you need\n     * to wait until the next tick. If you try to add it back in during\n     * the `dispose()` function call, it will break things in subtle and\n     * weird ways.\n     *\n     * Unlike several other options, this may _not_ be overridden by\n     * passing an option to `set()`, for performance reasons.\n     *\n     * The `reason` will be one of the following strings, corresponding\n     * to the reason for the item's deletion:\n     *\n     * - `evict` Item was evicted to make space for a new addition\n     * - `set` Item was overwritten by a new value\n     * - `expire` Item expired its TTL\n     * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n     *   fetchMethod returning `undefined.\n     * - `delete` Item was removed by explicit `cache.delete(key)`,\n     *   `cache.clear()`, or `cache.set(key, undefined)`.\n     */\n    dispose?: Disposer\n\n    /**\n     * Function that is called when new items are inserted into the cache,\n     * as `onInsert(value, key, reason)`.\n     *\n     * This can be useful if you need to perform actions when an item is\n     * added, such as logging or tracking insertions.\n     *\n     * Unlike some other options, this may _not_ be overridden by passing\n     * an option to `set()`, for performance and consistency reasons.\n     */\n    onInsert?: Inserter\n\n    /**\n     * The same as {@link OptionsBase.dispose}, but called *after* the entry\n     * is completely removed and the cache is once again in a clean state.\n     *\n     * It is safe to add an item right back into the cache at this point.\n     * However, note that it is *very* easy to inadvertently create infinite\n     * recursion this way.\n     */\n    disposeAfter?: Disposer\n\n    /**\n     * Set to true to suppress calling the\n     * {@link OptionsBase.dispose} function if the entry key is\n     * still accessible within the cache.\n     *\n     * This may be overridden by passing an options object to\n     * {@link LRUCache#set}.\n     *\n     * Only relevant if `dispose` or `disposeAfter` are set.\n     */\n    noDisposeOnSet?: boolean\n\n    /**\n     * Boolean flag to tell the cache to not update the TTL when setting a new\n     * value for an existing key (ie, when updating a value rather than\n     * inserting a new value).  Note that the TTL value is _always_ set (if\n     * provided) when adding a new entry into the cache.\n     *\n     * Has no effect if a {@link OptionsBase.ttl} is not set.\n     *\n     * May be passed as an option to {@link LRUCache#set}.\n     */\n    noUpdateTTL?: boolean\n\n    /**\n     * Set to a positive integer to track the sizes of items added to the\n     * cache, and automatically evict items in order to stay below this size.\n     * Note that this may result in fewer than `max` items being stored.\n     *\n     * Attempting to add an item to the cache whose calculated size is greater\n     * that this amount will be a no-op. The item will not be cached, and no\n     * other items will be evicted.\n     *\n     * Optional, must be a positive integer if provided.\n     *\n     * Sets `maxEntrySize` to the same value, unless a different value is\n     * provided for `maxEntrySize`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if size tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * Note also that size tracking can negatively impact performance,\n     * though for most cases, only minimally.\n     */\n    maxSize?: Size\n\n    /**\n     * The effective size for background fetch promises.\n     *\n     * This has no effect unless `maxSize` and `sizeCalculation` are used,\n     * and a {@link LRUCache.OptionsBase.fetchMethod} is provided to\n     * support {@link LRUCache#fetch}.\n     *\n     * If a stale value is present in the cache, then the effective size of\n     * the background fetch is the size of the stale item it will eventually\n     * replace. If not, then this value is used as its effective size.\n     *\n     * @default 1\n     */\n    backgroundFetchSize?: number\n\n    /**\n     * The maximum allowed size for any single item in the cache.\n     *\n     * If a larger item is passed to {@link LRUCache#set} or returned by a\n     * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n     * it will not be stored in the cache.\n     *\n     * Attempting to add an item whose calculated size is greater than\n     * this amount will not cache the item or evict any old items, but\n     * WILL delete an existing value if one is already present.\n     *\n     * Optional, must be a positive integer if provided. Defaults to\n     * the value of `maxSize` if provided.\n     */\n    maxEntrySize?: Size\n\n    /**\n     * A function that returns a number indicating the item's size.\n     *\n     * Requires {@link OptionsBase.maxSize} to be set.\n     *\n     * If not provided, and {@link OptionsBase.maxSize} or\n     * {@link OptionsBase.maxEntrySize} are set, then all\n     * {@link LRUCache#set} calls **must** provide an explicit\n     * {@link SetOptions.size} or sizeCalculation param.\n     */\n    sizeCalculation?: SizeCalculator\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#fetch}\n     *\n     * ```ts\n     * fetchMethod(key, staleValue, { signal, options, context })\n     * ```\n     *\n     * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n     * to `Promise.resolve(cache.get(key))`.\n     *\n     * If at any time, `signal.aborted` is set to `true`, or if the\n     * `signal.onabort` method is called, or if it emits an `'abort'` event\n     * which you can listen to with `addEventListener`, then that means that\n     * the fetch should be abandoned. This may be passed along to async\n     * functions aware of AbortController/AbortSignal behavior.\n     *\n     * The `fetchMethod` should **only** return `undefined` or a Promise\n     * resolving to `undefined` if the AbortController signaled an `abort`\n     * event. In all other cases, it should return or resolve to a value\n     * suitable for adding to the cache.\n     *\n     * The `options` object is a union of the options that may be provided to\n     * `set()` and `get()`. If they are modified, then that will result in\n     * modifying the settings to `cache.set()` when the value is resolved, and\n     * in the case of\n     * {@link OptionsBase.noDeleteOnFetchRejection} and\n     * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n     * `fetchMethod` failures.\n     *\n     * For example, a DNS cache may update the TTL based on the value returned\n     * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n     */\n    fetchMethod?: Fetcher\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#memo}\n     */\n    memoMethod?: Memoizer\n\n    /**\n     * Set to true to suppress the deletion of stale data when a\n     * {@link OptionsBase.fetchMethod} returns a rejected promise.\n     */\n    noDeleteOnFetchRejection?: boolean\n\n    /**\n     * Do not delete stale items when they are retrieved with\n     * {@link LRUCache#get}.\n     *\n     * Note that the `get` return value will still be `undefined`\n     * unless {@link OptionsBase.allowStale} is true.\n     *\n     * When using time-expiring entries with `ttl`, by default stale\n     * items will be removed from the cache when the key is accessed\n     * with `cache.get()`.\n     *\n     * Setting this option will cause stale items to remain in the cache, until\n     * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n     * `noDeleteOnStaleGet` set to `false`.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     *\n     * Only relevant if a ttl is used.\n     */\n    noDeleteOnStaleGet?: boolean\n\n    /**\n     * Set to true to allow returning stale data when a\n     * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n     * promise.\n     *\n     * This differs from using {@link OptionsBase.allowStale} in that stale\n     * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n     * fails, not any other times.\n     *\n     * If a `fetchMethod` fails, and there is no stale value available, the\n     * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n     * suppressed.\n     *\n     * Implies `noDeleteOnFetchRejection`.\n     *\n     * This may be set in calls to `fetch()`, or defaulted on the constructor,\n     * or overridden by modifying the options object in the `fetchMethod`.\n     */\n    allowStaleOnFetchRejection?: boolean\n\n    /**\n     * Set to true to return a stale value from the cache when the\n     * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n     * an `'abort'` event, whether user-triggered, or due to internal cache\n     * behavior.\n     *\n     * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n     * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n     * any value it returns will be ignored and not cached.\n     *\n     * Caveat: since fetches are aborted when a new value is explicitly\n     * set in the cache, this can lead to fetch returning a stale value,\n     * since that was the fallback value _at the moment the `fetch()` was\n     * initiated_, even though the new updated value is now present in\n     * the cache.\n     *\n     * For example:\n     *\n     * ```ts\n     * const cache = new LRUCache({\n     *   ttl: 100,\n     *   fetchMethod: async (url, oldValue, { signal }) =>  {\n     *     const res = await fetch(url, { signal })\n     *     return await res.json()\n     *   }\n     * })\n     * cache.set('https://example.com/', { some: 'data' })\n     * // 100ms go by...\n     * const result = cache.fetch('https://example.com/')\n     * cache.set('https://example.com/', { other: 'thing' })\n     * console.log(await result) // { some: 'data' }\n     * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n     * ```\n     */\n    allowStaleOnFetchAbort?: boolean\n\n    /**\n     * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n     * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n     * resulting resolution value, as long as it is not `undefined`.\n     *\n     * When used on its own, this means aborted {@link LRUCache#fetch} calls\n     * are not immediately resolved or rejected when they are aborted, and\n     * instead take the full time to await.\n     *\n     * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n     * {@link LRUCache#fetch} calls will resolve immediately to their stale\n     * cached value or `undefined`, and will continue to process and eventually\n     * update the cache when they resolve, as long as the resulting value is\n     * not `undefined`, thus supporting a \"return stale on timeout while\n     * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n     *\n     * For example:\n     *\n     * ```ts\n     * const c = new LRUCache({\n     *   ttl: 100,\n     *   ignoreFetchAbort: true,\n     *   allowStaleOnFetchAbort: true,\n     *   fetchMethod: async (key, oldValue, { signal }) => {\n     *     // note: do NOT pass the signal to fetch()!\n     *     // let's say this fetch can take a long time.\n     *     const res = await fetch(`https://slow-backend-server/${key}`)\n     *     return await res.json()\n     *   },\n     * })\n     *\n     * // this will return the stale value after 100ms, while still\n     * // updating in the background for next time.\n     * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n     * ```\n     *\n     * **Note**: regardless of this setting, an `abort` event _is still\n     * emitted on the `AbortSignal` object_, so may result in invalid results\n     * when passed to other underlying APIs that use AbortSignals.\n     *\n     * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n     * call to {@link LRUCache#fetch}.\n     */\n    ignoreFetchAbort?: boolean\n\n    /**\n     * In some cases, you may want to swap out the performance/Date object\n     * used for TTL tracking. This should almost certainly NOT be done in\n     * production environments!\n     *\n     * This value defaults to `global.performance` if it has a `now()` method,\n     * or the `global.Date` object otherwise.\n     */\n    perf?: Perf\n  }\n\n  export interface OptionsMaxLimit extends OptionsBase<\n    K,\n    V,\n    FC\n  > {\n    max: Count\n  }\n  export interface OptionsTTLLimit extends OptionsBase<\n    K,\n    V,\n    FC\n  > {\n    ttl: Milliseconds\n    ttlAutopurge: boolean\n  }\n  export interface OptionsSizeLimit extends OptionsBase<\n    K,\n    V,\n    FC\n  > {\n    maxSize: Size\n  }\n\n  /**\n   * The valid safe options for the {@link LRUCache} constructor\n   */\n  export type Options =\n    | OptionsMaxLimit\n    | OptionsSizeLimit\n    | OptionsTTLLimit\n\n  /**\n   * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n   * and returned by {@link LRUCache#info}.\n   */\n  export interface Entry {\n    value: V\n    ttl?: Milliseconds\n    size?: Size\n    start?: Milliseconds\n  }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache {\n  // options that cannot be changed without disaster\n  readonly #max: LRUCache.Count\n  readonly #maxSize: LRUCache.Size\n  readonly #dispose?: LRUCache.Disposer\n  readonly #onInsert?: LRUCache.Inserter\n  readonly #disposeAfter?: LRUCache.Disposer\n  readonly #fetchMethod?: LRUCache.Fetcher\n  readonly #memoMethod?: LRUCache.Memoizer\n  readonly #perf: Perf\n\n  /**\n   * {@link LRUCache.OptionsBase.perf}\n   */\n  get perf() {\n    return this.#perf\n  }\n\n  /**\n   * {@link LRUCache.OptionsBase.ttl}\n   */\n  ttl: LRUCache.Milliseconds\n\n  /**\n   * {@link LRUCache.OptionsBase.ttlResolution}\n   */\n  ttlResolution: LRUCache.Milliseconds\n  /**\n   * {@link LRUCache.OptionsBase.ttlAutopurge}\n   */\n  ttlAutopurge: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnGet}\n   */\n  updateAgeOnGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnHas}\n   */\n  updateAgeOnHas: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStale}\n   */\n  allowStale: boolean\n\n  /**\n   * {@link LRUCache.OptionsBase.noDisposeOnSet}\n   */\n  noDisposeOnSet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noUpdateTTL}\n   */\n  noUpdateTTL: boolean\n  /**\n   * {@link LRUCache.OptionsBase.maxEntrySize}\n   */\n  maxEntrySize: LRUCache.Size\n  /**\n   * {@link LRUCache.OptionsBase.sizeCalculation}\n   */\n  sizeCalculation?: LRUCache.SizeCalculator\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n   */\n  noDeleteOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n   */\n  noDeleteOnStaleGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n   */\n  allowStaleOnFetchAbort: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n   */\n  allowStaleOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n   */\n  ignoreFetchAbort: boolean\n\n  /** {@link LRUCache.OptionsBase.backgroundFetchSize} */\n  backgroundFetchSize: number\n\n  // computed properties\n  #size: LRUCache.Count\n  #calculatedSize: LRUCache.Size\n  #keyMap: Map\n  #keyList: (K | undefined)[]\n  #valList: (V | BackgroundFetch | undefined)[]\n  #next: NumberArray\n  #prev: NumberArray\n  #head: Index\n  #tail: Index\n  #free: StackLike\n  #disposed?: DisposeTask[]\n  #sizes?: ZeroArray\n  #starts?: ZeroArray\n  #ttls?: ZeroArray\n  #autopurgeTimers?: (undefined | ReturnType)[]\n\n  #hasDispose: boolean\n  #hasFetchMethod: boolean\n  #hasDisposeAfter: boolean\n  #hasOnInsert: boolean\n\n  /**\n   * Do not call this method unless you need to inspect the\n   * inner workings of the cache.  If anything returned by this\n   * object is modified in any way, strange breakage may occur.\n   *\n   * These fields are private for a reason!\n   *\n   * @internal\n   */\n  static unsafeExposeInternals<\n    K extends {},\n    V extends {},\n    FC extends unknown = unknown,\n  >(c: LRUCache) {\n    return {\n      // properties\n      starts: c.#starts,\n      ttls: c.#ttls,\n      autopurgeTimers: c.#autopurgeTimers,\n      sizes: c.#sizes,\n      keyMap: c.#keyMap as Map,\n      keyList: c.#keyList,\n      valList: c.#valList,\n      next: c.#next,\n      prev: c.#prev,\n      get head() {\n        return c.#head\n      },\n      get tail() {\n        return c.#tail\n      },\n      free: c.#free,\n      // methods\n      isBackgroundFetch: (p: unknown) => c.#isBackgroundFetch(p),\n      backgroundFetch: (\n        k: K,\n        index: number | undefined,\n        options: LRUCache.FetchOptions,\n        context: unknown,\n      ): BackgroundFetch =>\n        c.#backgroundFetch(\n          k,\n          index as Index | undefined,\n          options,\n          context as FC,\n        ),\n      moveToTail: (index: number): void => c.#moveToTail(index as Index),\n      indexes: (options?: { allowStale: boolean }) => c.#indexes(options),\n      rindexes: (options?: { allowStale: boolean }) =>\n        c.#rindexes(options),\n      isStale: (index: number | undefined) => c.#isStale(index as Index),\n    }\n  }\n\n  // Protected read-only members\n\n  /**\n   * {@link LRUCache.OptionsBase.max} (read-only)\n   */\n  get max(): LRUCache.Count {\n    return this.#max\n  }\n  /**\n   * {@link LRUCache.OptionsBase.maxSize} (read-only)\n   */\n  get maxSize(): LRUCache.Count {\n    return this.#maxSize\n  }\n  /**\n   * The total computed size of items in the cache (read-only)\n   */\n  get calculatedSize(): LRUCache.Size {\n    return this.#calculatedSize\n  }\n  /**\n   * The number of items stored in the cache (read-only)\n   */\n  get size(): LRUCache.Count {\n    return this.#size\n  }\n  /**\n   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n   */\n  get fetchMethod(): LRUCache.Fetcher | undefined {\n    return this.#fetchMethod\n  }\n  get memoMethod(): LRUCache.Memoizer | undefined {\n    return this.#memoMethod\n  }\n  /**\n   * {@link LRUCache.OptionsBase.dispose} (read-only)\n   */\n  get dispose() {\n    return this.#dispose\n  }\n  /**\n   * {@link LRUCache.OptionsBase.onInsert} (read-only)\n   */\n  get onInsert() {\n    return this.#onInsert\n  }\n  /**\n   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n   */\n  get disposeAfter() {\n    return this.#disposeAfter\n  }\n\n  constructor(options: LRUCache.Options | LRUCache) {\n    const {\n      max = 0,\n      ttl,\n      ttlResolution = 1,\n      ttlAutopurge,\n      updateAgeOnGet,\n      updateAgeOnHas,\n      allowStale,\n      dispose,\n      onInsert,\n      disposeAfter,\n      noDisposeOnSet,\n      noUpdateTTL,\n      maxSize = 0,\n      maxEntrySize = 0,\n      sizeCalculation,\n      fetchMethod,\n      memoMethod,\n      noDeleteOnFetchRejection,\n      noDeleteOnStaleGet,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      backgroundFetchSize = 1,\n      perf,\n    } = options\n\n    this.backgroundFetchSize = backgroundFetchSize\n\n    if (perf !== undefined) {\n      if (typeof perf?.now !== 'function') {\n        throw new TypeError(\n          'perf option must have a now() method if specified',\n        )\n      }\n    }\n\n    this.#perf = perf ?? defaultPerf\n\n    if (max !== 0 && !isPosInt(max)) {\n      throw new TypeError('max option must be a nonnegative integer')\n    }\n\n    const UintArray = max ? getUintArray(max) : Array\n    if (!UintArray) {\n      throw new Error('invalid max value: ' + max)\n    }\n\n    this.#max = max\n    this.#maxSize = maxSize\n    this.maxEntrySize = maxEntrySize || this.#maxSize\n    this.sizeCalculation = sizeCalculation\n    if (this.sizeCalculation) {\n      if (!this.#maxSize && !this.maxEntrySize) {\n        throw new TypeError(\n          'cannot set sizeCalculation without setting maxSize or maxEntrySize',\n        )\n      }\n      if (typeof this.sizeCalculation !== 'function') {\n        throw new TypeError('sizeCalculation set to non-function')\n      }\n    }\n\n    if (memoMethod !== undefined && typeof memoMethod !== 'function') {\n      throw new TypeError('memoMethod must be a function if defined')\n    }\n    this.#memoMethod = memoMethod\n\n    if (fetchMethod !== undefined && typeof fetchMethod !== 'function') {\n      throw new TypeError('fetchMethod must be a function if specified')\n    }\n    this.#fetchMethod = fetchMethod\n    this.#hasFetchMethod = !!fetchMethod\n\n    this.#keyMap = new Map()\n    this.#keyList = Array.from({ length: max }).fill(undefined) as (\n      | K\n      | undefined\n    )[]\n    this.#valList = Array.from({ length: max }).fill(undefined) as (\n      | V\n      | undefined\n    )[]\n    this.#next = new UintArray(max)\n    this.#prev = new UintArray(max)\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free = Stack.create(max)\n    this.#size = 0\n    this.#calculatedSize = 0\n\n    if (typeof dispose === 'function') {\n      this.#dispose = dispose\n    }\n    if (typeof onInsert === 'function') {\n      this.#onInsert = onInsert\n    }\n    if (typeof disposeAfter === 'function') {\n      this.#disposeAfter = disposeAfter\n      this.#disposed = []\n    } else {\n      this.#disposeAfter = undefined\n      this.#disposed = undefined\n    }\n    this.#hasDispose = !!this.#dispose\n    this.#hasOnInsert = !!this.#onInsert\n    this.#hasDisposeAfter = !!this.#disposeAfter\n\n    this.noDisposeOnSet = !!noDisposeOnSet\n    this.noUpdateTTL = !!noUpdateTTL\n    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n    this.ignoreFetchAbort = !!ignoreFetchAbort\n\n    // NB: maxEntrySize is set to maxSize if it's set\n    if (this.maxEntrySize !== 0) {\n      if (this.#maxSize !== 0) {\n        if (!isPosInt(this.#maxSize)) {\n          throw new TypeError(\n            'maxSize must be a positive integer if specified',\n          )\n        }\n      }\n      if (!isPosInt(this.maxEntrySize)) {\n        throw new TypeError(\n          'maxEntrySize must be a positive integer if specified',\n        )\n      }\n      this.#initializeSizeTracking()\n    }\n\n    this.allowStale = !!allowStale\n    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n    this.updateAgeOnGet = !!updateAgeOnGet\n    this.updateAgeOnHas = !!updateAgeOnHas\n    this.ttlResolution =\n      isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1\n    this.ttlAutopurge = !!ttlAutopurge\n    this.ttl = ttl || 0\n    if (this.ttl) {\n      if (!isPosInt(this.ttl)) {\n        throw new TypeError('ttl must be a positive integer if specified')\n      }\n      this.#initializeTTLTracking()\n    }\n\n    // do not allow completely unbounded caches\n    if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n      throw new TypeError(\n        'At least one of max, maxSize, or ttl is required',\n      )\n    }\n    if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n      const code = 'LRU_CACHE_UNBOUNDED'\n      if (shouldWarn(code)) {\n        warned.add(code)\n        const msg =\n          'TTL caching without ttlAutopurge, max, or maxSize can ' +\n          'result in unbounded memory consumption.'\n        emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n      }\n    }\n  }\n\n  /**\n   * Return the number of ms left in the item's TTL. If item is not in cache,\n   * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n   */\n  getRemainingTTL(key: K) {\n    return this.#keyMap.has(key) ? Infinity : 0\n  }\n\n  #initializeTTLTracking() {\n    const ttls = new ZeroArray(this.#max)\n    const starts = new ZeroArray(this.#max)\n    this.#ttls = ttls\n    this.#starts = starts\n    const purgeTimers =\n      this.ttlAutopurge ?\n        Array.from>({\n          length: this.#max,\n        })\n      : undefined\n    this.#autopurgeTimers = purgeTimers\n\n    this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {\n      starts[index] = ttl !== 0 ? start : 0\n      ttls[index] = ttl\n      setPurgeTimer(index, ttl)\n    }\n\n    this.#updateItemAge = index => {\n      starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0\n      setPurgeTimer(index, ttls[index])\n    }\n\n    // clear out the purge timer if we're setting TTL to 0, and\n    // previously had a ttl purge timer running, so it doesn't\n    // fire unnecessarily. Don't need to do this if we're not doing\n    // autopurge.\n    const setPurgeTimer =\n      !this.ttlAutopurge ?\n        () => {}\n      : (index: Index, ttl?: number) => {\n          if (purgeTimers?.[index]) {\n            clearTimeout(purgeTimers[index])\n            purgeTimers[index] = undefined\n          }\n          if (ttl && ttl !== 0 && purgeTimers) {\n            const t = setTimeout(() => {\n              if (this.#isStale(index)) {\n                this.#delete(this.#keyList[index] as K, 'expire')\n                purgeTimers[index] = undefined\n              } else {\n                setPurgeTimer(index, getRemainingTTL(index))\n              }\n            }, ttl + 1)\n            // unref() not supported on all platforms\n            /* c8 ignore start */\n            if (t.unref) {\n              t.unref()\n            }\n            /* c8 ignore stop */\n            purgeTimers[index] = t\n          }\n        }\n\n    this.#statusTTL = (status, index) => {\n      if (ttls[index]) {\n        const ttl = ttls[index]\n        const start = starts[index]\n        /* c8 ignore start */\n        if (!ttl || !start) {\n          return\n        }\n        /* c8 ignore stop */\n        status.ttl = ttl\n        status.start = start\n        status.now = cachedNow || getNow()\n        const age = status.now - start\n        status.remainingTTL = ttl - age\n      }\n    }\n\n    // debounce calls to perf.now() to 1s so we're not hitting\n    // that costly call repeatedly.\n    let cachedNow = 0\n    const getNow = () => {\n      const n = this.#perf.now()\n      if (this.ttlResolution > 0) {\n        cachedNow = n\n        const t = setTimeout(() => (cachedNow = 0), this.ttlResolution)\n        // not available on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n      return n\n    }\n\n    this.getRemainingTTL = key => {\n      const index = this.#keyMap.get(key)\n      if (index === undefined) {\n        return 0\n      }\n      return getRemainingTTL(index)\n    }\n    const getRemainingTTL = (index: Index) => {\n      const ttl = ttls[index]\n      const start = starts[index]\n      if (!ttl || !start) {\n        return Infinity\n      }\n      const age = (cachedNow || getNow()) - start\n      return ttl - age\n    }\n\n    this.#isStale = index => {\n      const s = starts[index]\n      const t = ttls[index]\n      return !!t && !!s && (cachedNow || getNow()) - s > t\n    }\n  }\n\n  // conditionally set private methods related to TTL\n  #updateItemAge: (index: Index) => void = () => {}\n  #statusTTL: (status: LRUCache.Status, index: Index) => void =\n    () => {}\n  #setItemTTL: (\n    index: Index,\n    ttl: LRUCache.Milliseconds,\n    start?: LRUCache.Milliseconds,\n    // ignore because we never call this if we're not already in TTL mode\n    /* c8 ignore start */\n  ) => void = () => {}\n  /* c8 ignore stop */\n\n  #isStale: (index: Index) => boolean = () => false\n\n  #initializeSizeTracking() {\n    const sizes = new ZeroArray(this.#max)\n    this.#calculatedSize = 0\n    this.#sizes = sizes\n    this.#removeItemSize = index => {\n      this.#calculatedSize -= sizes[index] as number\n      sizes[index] = 0\n    }\n    this.#requireSize = (k, v, size, sizeCalculation) => {\n      if (!isPosInt(size)) {\n        // provisionally accept background fetches.\n        // actual value size will be checked when they return.\n        if (this.#isBackgroundFetch(v)) {\n          // NB: this cannot occur if v.__staleWhileFetching is set,\n          // because in that case, it would take on the size of the\n          // existing entry that it temporarily replaces.\n          return this.backgroundFetchSize\n        }\n        if (sizeCalculation) {\n          if (typeof sizeCalculation !== 'function') {\n            throw new TypeError('sizeCalculation must be a function')\n          }\n          size = sizeCalculation(v, k)\n          if (!isPosInt(size)) {\n            throw new TypeError(\n              'sizeCalculation return invalid (expect positive integer)',\n            )\n          }\n        } else {\n          throw new TypeError(\n            'invalid size value (must be positive integer). ' +\n              'When maxSize or maxEntrySize is used, sizeCalculation ' +\n              'or size must be set.',\n          )\n        }\n      }\n      return size\n    }\n\n    this.#addItemSize = (\n      index: Index,\n      size: LRUCache.Size,\n      status?: LRUCache.Status,\n    ) => {\n      sizes[index] = size\n      if (this.#maxSize) {\n        const maxSize = this.#maxSize - sizes[index]\n        while (this.#calculatedSize > maxSize) {\n          this.#evict(true)\n        }\n      }\n      this.#calculatedSize += sizes[index]\n      if (status) {\n        status.entrySize = size\n        status.totalCalculatedSize = this.#calculatedSize\n      }\n    }\n  }\n\n  #removeItemSize: (index: Index) => void = _i => {}\n\n  #addItemSize: (\n    index: Index,\n    size: LRUCache.Size,\n    status?: LRUCache.Status,\n  ) => void = (_i, _s, _st) => {}\n\n  #requireSize: (\n    k: K,\n    v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator,\n    status?: LRUCache.Status,\n  ) => LRUCache.Size = (\n    _k: K,\n    _v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator,\n  ) => {\n    if (size || sizeCalculation) {\n      throw new TypeError(\n        'cannot set size without setting maxSize or maxEntrySize on cache',\n      )\n    }\n    return 0\n  };\n\n  *#indexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#tail; this.#isValidIndex(i); ) {\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#head) {\n          break\n        } else {\n          i = this.#prev[i] as Index\n        }\n      }\n    }\n  }\n\n  *#rindexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#head; this.#isValidIndex(i); ) {\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#tail) {\n          break\n        } else {\n          i = this.#next[i] as Index\n        }\n      }\n    }\n  }\n\n  #isValidIndex(index: Index) {\n    return (\n      index !== undefined &&\n      this.#keyMap.get(this.#keyList[index] as K) === index\n    )\n  }\n\n  /**\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from most recently used to least recently used.\n   */\n  *entries() {\n    for (const i of this.#indexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]] as [K, V]\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.entries}\n   *\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from least recently used to most recently used.\n   */\n  *rentries() {\n    for (const i of this.#rindexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]]\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the keys in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *keys() {\n    for (const i of this.#indexes()) {\n      const k = this.#keyList[i]\n      if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.keys}\n   *\n   * Return a generator yielding the keys in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rkeys() {\n    for (const i of this.#rindexes()) {\n      const k = this.#keyList[i]\n      if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the values in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *values() {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield this.#valList[i] as V\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.values}\n   *\n   * Return a generator yielding the values in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rvalues() {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield this.#valList[i]\n      }\n    }\n  }\n\n  /**\n   * Iterating over the cache itself yields the same results as\n   * {@link LRUCache.entries}\n   */\n  [Symbol.iterator]() {\n    return this.entries()\n  }\n\n  /**\n   * A String value that is used in the creation of the default string\n   * description of an object. Called by the built-in method\n   * `Object.prototype.toString`.\n   */\n  [Symbol.toStringTag] = 'LRUCache'\n\n  /**\n   * Find a value for which the supplied fn method returns a truthy value,\n   * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n   */\n  find(\n    fn: (v: V, k: K, self: LRUCache) => boolean,\n    getOptions: LRUCache.GetOptions = {},\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      if (fn(value, this.#keyList[i] as K, this)) {\n        return this.#get(this.#keyList[i] as K, getOptions)\n      }\n    }\n  }\n\n  /**\n   * Call the supplied function on each item in the cache, in order from most\n   * recently used to least recently used.\n   *\n   * `fn` is called as `fn(value, key, cache)`.\n   *\n   * If `thisp` is provided, function will be called in the `this`-context of\n   * the provided object, or the cache if no `thisp` object is provided.\n   *\n   * Does not update age or recenty of use, or iterate over stale values.\n   */\n  forEach(\n    fn: (v: V, k: K, self: LRUCache) => unknown,\n    thisp: unknown = this,\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * The same as {@link LRUCache.forEach} but items are iterated over in\n   * reverse order.  (ie, less recently used items are iterated over first.)\n   */\n  rforEach(\n    fn: (v: V, k: K, self: LRUCache) => unknown,\n    thisp: unknown = this,\n  ) {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * Delete any stale entries. Returns true if anything was removed,\n   * false otherwise.\n   */\n  purgeStale() {\n    let deleted = false\n    for (const i of this.#rindexes({ allowStale: true })) {\n      if (this.#isStale(i)) {\n        this.#delete(this.#keyList[i] as K, 'expire')\n        deleted = true\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Get the extended info about a given entry, to get its value, size, and\n   * TTL info simultaneously. Returns `undefined` if the key is not present.\n   *\n   * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n   * serialization, the `start` value is always the current timestamp, and the\n   * `ttl` is a calculated remaining time to live (negative if expired).\n   *\n   * Always returns stale values, if their info is found in the cache, so be\n   * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n   * if relevant.\n   */\n  info(key: K): LRUCache.Entry | undefined {\n    const i = this.#keyMap.get(key)\n    if (i === undefined) return undefined\n    const v = this.#valList[i]\n    /* c8 ignore start - this isn't tested for the info function,\n     * but it's the same logic as found in other places. */\n    const value: V | undefined =\n      this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n    if (value === undefined) return undefined\n    /* c8 ignore stop */\n    const entry: LRUCache.Entry = { value }\n    if (this.#ttls && this.#starts) {\n      const ttl = this.#ttls[i]\n      const start = this.#starts[i]\n      if (ttl && start) {\n        const remain = ttl - (this.#perf.now() - start)\n        entry.ttl = remain\n        entry.start = Date.now()\n      }\n    }\n    if (this.#sizes) {\n      entry.size = this.#sizes[i]\n    }\n    return entry\n  }\n\n  /**\n   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n   * passed to {@link LRUCache#load}.\n   *\n   * The `start` fields are calculated relative to a portable `Date.now()`\n   * timestamp, even if `performance.now()` is available.\n   *\n   * Stale entries are always included in the `dump`, even if\n   * {@link LRUCache.OptionsBase.allowStale} is false.\n   *\n   * Note: this returns an actual array, not a generator, so it can be more\n   * easily passed around.\n   */\n  dump() {\n    const arr: [K, LRUCache.Entry][] = []\n    for (const i of this.#indexes({ allowStale: true })) {\n      const key = this.#keyList[i]\n      const v = this.#valList[i]\n      const value: V | undefined =\n        this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined || key === undefined) continue\n      const entry: LRUCache.Entry = { value }\n      if (this.#ttls && this.#starts) {\n        entry.ttl = this.#ttls[i]\n        // always dump the start relative to a portable timestamp\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = this.#perf.now() - (this.#starts[i] as number)\n        entry.start = Math.floor(Date.now() - age)\n      }\n      if (this.#sizes) {\n        entry.size = this.#sizes[i]\n      }\n      arr.unshift([key, entry])\n    }\n    return arr\n  }\n\n  /**\n   * Reset the cache and load in the items in entries in the order listed.\n   *\n   * The shape of the resulting cache may be different if the same options are\n   * not used in both caches.\n   *\n   * The `start` fields are assumed to be calculated relative to a portable\n   * `Date.now()` timestamp, even if `performance.now()` is available.\n   */\n  load(arr: [K, LRUCache.Entry][]) {\n    this.clear()\n    for (const [key, entry] of arr) {\n      if (entry.start) {\n        // entry.start is a portable timestamp, but we may be using\n        // node's performance.now(), so calculate the offset, so that\n        // we get the intended remaining TTL, no matter how long it's\n        // been on ice.\n        //\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = Date.now() - entry.start\n        entry.start = this.#perf.now() - age\n      }\n      this.#set(key, entry.value, entry)\n    }\n  }\n\n  /**\n   * Add a value to the cache.\n   *\n   * Note: if `undefined` is specified as a value, this is an alias for\n   * {@link LRUCache#delete}\n   *\n   * Fields on the {@link LRUCache.SetOptions} options param will override\n   * their corresponding values in the constructor options for the scope\n   * of this single `set()` operation.\n   *\n   * If `start` is provided, then that will set the effective start\n   * time for the TTL calculation. Note that this must be a previous\n   * value of `performance.now()` if supported, or a previous value of\n   * `Date.now()` if not.\n   *\n   * Options object may also include `size`, which will prevent\n   * calling the `sizeCalculation` function and just use the specified\n   * number if it is a positive integer, and `noDisposeOnSet` which\n   * will prevent calling a `dispose` function in the case of\n   * overwrites.\n   *\n   * If the `size` (or return value of `sizeCalculation`) for a given\n   * entry is greater than `maxEntrySize`, then the item will not be\n   * added to the cache.\n   *\n   * Will update the recency of the entry.\n   *\n   * If the value is `undefined`, then this is an alias for\n   * `cache.delete(key)`. `undefined` is never stored in the cache.\n   */\n  set(\n    k: K,\n    v: V | undefined,\n    setOptions: LRUCache.SetOptions = {},\n  ) {\n    const { status = metrics.hasSubscribers ? {} : undefined } = setOptions\n    setOptions.status = status\n    if (status) {\n      status.op = 'set'\n      status.key = k\n      if (v !== undefined) status.value = v\n      status.cache = this\n    }\n    const result = this.#set(k, v, setOptions)\n    if (status && metrics.hasSubscribers) {\n      metrics.publish(status)\n    }\n    return result\n  }\n\n  #set(\n    k: K,\n    v: V | BackgroundFetch | undefined,\n    setOptions: LRUCache.SetOptions,\n    bf?: BackgroundFetch,\n  ) {\n    const {\n      ttl = this.ttl,\n      start,\n      noDisposeOnSet = this.noDisposeOnSet,\n      sizeCalculation = this.sizeCalculation,\n      status,\n    } = setOptions\n\n    const isBF = this.#isBackgroundFetch(v)\n    if (v === undefined) {\n      if (status) status.set = 'deleted'\n      this.delete(k)\n      return this\n    }\n    let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n    if (status && !isBF) status.value = v\n\n    const size = this.#requireSize(\n      k,\n      v,\n      setOptions.size || 0,\n      sizeCalculation,\n      status,\n    )\n    // if the item doesn't fit, don't do anything\n    // NB: maxEntrySize set to maxSize by default\n    if (this.maxEntrySize && size > this.maxEntrySize) {\n      // have to delete, in case something is there already.\n      this.#delete(k, 'set')\n      if (status) {\n        status.set = 'miss'\n        status.maxEntrySizeExceeded = true\n      }\n      return this\n    }\n    let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n    if (index === undefined) {\n      // addition\n      index = (\n        this.#size === 0 ? this.#tail\n        : this.#free.length !== 0 ? this.#free.pop()\n        : this.#size === this.#max ? this.#evict(false)\n        : this.#size) as Index\n      this.#keyList[index] = k\n      this.#valList[index] = v\n      this.#keyMap.set(k, index)\n      this.#next[this.#tail] = index\n      this.#prev[index] = this.#tail\n      this.#tail = index\n      this.#size++\n      this.#addItemSize(index, size, status)\n      if (status) status.set = 'add'\n      noUpdateTTL = false\n      if (this.#hasOnInsert && !isBF) {\n        this.#onInsert?.(v, k, 'add')\n      }\n    } else {\n      // update\n      // might be updating a background fetch!\n      this.#moveToTail(index)\n      const oldVal = this.#valList[index]!\n      if (v !== oldVal) {\n        if (!noDisposeOnSet) {\n          if (this.#isBackgroundFetch(oldVal)) {\n            if (oldVal !== bf) {\n              // setting over a background fetch, not merely resolving it.\n              oldVal.__abortController.abort(new Error('replaced'))\n            }\n            const { __staleWhileFetching: s } = oldVal\n            if (s !== undefined && s !== v) {\n              if (this.#hasDispose) {\n                this.#dispose?.(s, k, 'set')\n              }\n              if (this.#hasDisposeAfter) {\n                this.#disposed?.push([s, k, 'set'])\n              }\n            }\n          } else {\n            if (this.#hasDispose) {\n              this.#dispose?.(oldVal, k, 'set')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([oldVal, k, 'set'])\n            }\n          }\n        }\n        this.#removeItemSize(index)\n        this.#addItemSize(index, size, status)\n        this.#valList[index] = v\n        if (!isBF) {\n          const oldValue =\n            oldVal && this.#isBackgroundFetch(oldVal) ?\n              oldVal.__staleWhileFetching\n            : oldVal\n          const setType =\n            oldValue === undefined ? 'add'\n            : v !== oldValue ? 'replace'\n            : 'update'\n          if (status) {\n            status.set = setType\n            if (oldValue !== undefined) status.oldValue = oldValue\n          }\n          if (this.#hasOnInsert) {\n            this.onInsert?.(v, k, setType)\n          }\n        }\n      } else if (!isBF) {\n        if (status) {\n          status.set = 'update'\n        }\n        if (this.#hasOnInsert) {\n          this.onInsert?.(v, k, 'update')\n        }\n      }\n    }\n    if (ttl !== 0 && !this.#ttls) {\n      this.#initializeTTLTracking()\n    }\n    if (this.#ttls) {\n      if (!noUpdateTTL) {\n        this.#setItemTTL(index, ttl, start)\n      }\n      if (status) this.#statusTTL(status, index)\n    }\n    if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return this\n  }\n\n  /**\n   * Evict the least recently used item, returning its value or\n   * `undefined` if cache is empty.\n   */\n  pop(): V | undefined {\n    try {\n      while (this.#size) {\n        const val = this.#valList[this.#head]\n        this.#evict(true)\n        if (this.#isBackgroundFetch(val)) {\n          if (val.__staleWhileFetching) {\n            return val.__staleWhileFetching\n          }\n        } else if (val !== undefined) {\n          return val\n        }\n      }\n    } finally {\n      if (this.#hasDisposeAfter && this.#disposed) {\n        const dt = this.#disposed\n        let task: DisposeTask | undefined\n        while ((task = dt?.shift())) {\n          this.#disposeAfter?.(...task)\n        }\n      }\n    }\n  }\n\n  #evict(free: boolean) {\n    const head = this.#head\n    const k = this.#keyList[head]!\n    const v = this.#valList[head]!\n    const isBF = this.#isBackgroundFetch(v)\n    if (isBF) {\n      v.__abortController.abort(new Error('evicted'))\n    }\n    const oldValue = isBF ? v.__staleWhileFetching : v\n    if (\n      (this.#hasDispose || this.#hasDisposeAfter) &&\n      oldValue !== undefined\n    ) {\n      if (this.#hasDispose) {\n        this.#dispose?.(oldValue, k, 'evict')\n      }\n      if (this.#hasDisposeAfter) {\n        this.#disposed?.push([oldValue, k, 'evict'])\n      }\n    }\n    this.#removeItemSize(head)\n    if (this.#autopurgeTimers?.[head]) {\n      clearTimeout(this.#autopurgeTimers[head])\n      this.#autopurgeTimers[head] = undefined\n    }\n    // if we aren't about to use the index, then null these out\n    if (free) {\n      this.#keyList[head] = undefined\n      this.#valList[head] = undefined\n      this.#free.push(head)\n    }\n    if (this.#size === 1) {\n      this.#head = this.#tail = 0 as Index\n      this.#free.length = 0\n    } else {\n      this.#head = this.#next[head] as Index\n    }\n    this.#keyMap.delete(k)\n    this.#size--\n    return head\n  }\n\n  /**\n   * Check if a key is in the cache, without updating the recency of use.\n   * Will return false if the item is stale, even though it is technically\n   * in the cache.\n   *\n   * Check if a key is in the cache, without updating the recency of\n   * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n   * to `true` in either the options or the constructor.\n   *\n   * Will return `false` if the item is stale, even though it is technically in\n   * the cache. The difference can be determined (if it matters) by using a\n   * `status` argument, and inspecting the `has` field.\n   *\n   * Will not update item age unless\n   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n   */\n  has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { status = metrics.hasSubscribers ? {} : undefined } = hasOptions\n    hasOptions.status = status\n    if (status) {\n      status.op = 'has'\n      status.key = k\n      status.cache = this\n    }\n    const result = this.#has(k, hasOptions)\n    if (metrics.hasSubscribers) metrics.publish(status)\n    return result\n  }\n  #has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const v = this.#valList[index]\n      if (\n        this.#isBackgroundFetch(v) &&\n        v.__staleWhileFetching === undefined\n      ) {\n        return false\n      }\n      if (!this.#isStale(index)) {\n        if (updateAgeOnHas) {\n          this.#updateItemAge(index)\n        }\n        if (status) {\n          status.has = 'hit'\n          this.#statusTTL(status, index)\n        }\n        return true\n      } else if (status) {\n        status.has = 'stale'\n        this.#statusTTL(status, index)\n      }\n    } else if (status) {\n      status.has = 'miss'\n    }\n    return false\n  }\n\n  /**\n   * Like {@link LRUCache#get} but doesn't update recency or delete stale\n   * items.\n   *\n   * Returns `undefined` if the item is stale, unless\n   * {@link LRUCache.OptionsBase.allowStale} is set.\n   */\n  peek(k: K, peekOptions: LRUCache.PeekOptions = {}) {\n    const { status = hasSubscribers() ? {} : undefined } = peekOptions\n    if (status) {\n      status.op = 'peek'\n      status.key = k\n      status.cache = this\n    }\n    peekOptions.status = status\n    const result = this.#peek(k, peekOptions)\n    if (metrics.hasSubscribers) {\n      metrics.publish(status)\n    }\n    return result\n  }\n  #peek(k: K, peekOptions: LRUCache.PeekOptions) {\n    const { status, allowStale = this.allowStale } = peekOptions\n    const index = this.#keyMap.get(k)\n    if (index === undefined || (!allowStale && this.#isStale(index))) {\n      if (status) status.peek = index === undefined ? 'miss' : 'stale'\n      return undefined\n    }\n    const v = this.#valList[index]\n    const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n    if (status) {\n      if (val !== undefined) {\n        status.peek = 'hit'\n        status.value = val\n      } else {\n        status.peek = 'miss'\n      }\n    }\n    return val\n  }\n\n  #backgroundFetch(\n    k: K,\n    index: Index | undefined,\n    options: LRUCache.FetchOptions,\n    context: FC,\n  ): BackgroundFetch {\n    const v = index === undefined ? undefined : this.#valList[index]\n    if (this.#isBackgroundFetch(v)) {\n      return v\n    }\n\n    const ac = new AbortController()\n    const { signal } = options\n    // when/if our AC signals, then stop listening to theirs.\n    signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n      signal: ac.signal,\n    })\n\n    const fetchOpts = {\n      signal: ac.signal,\n      options,\n      context,\n    }\n\n    const cb = (v: V | undefined, updateCache = false): V | undefined => {\n      const { aborted } = ac.signal\n      const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n      const proceed =\n        options.ignoreFetchAbort ||\n        !!(options.allowStaleOnFetchAbort && v !== undefined)\n      if (options.status) {\n        if (aborted && !updateCache) {\n          options.status.fetchAborted = true\n          options.status.fetchError = ac.signal.reason\n          if (ignoreAbort) options.status.fetchAbortIgnored = true\n        } else {\n          options.status.fetchResolved = true\n        }\n      }\n      if (aborted && !ignoreAbort && !updateCache) {\n        return fetchFail(ac.signal.reason, proceed)\n      }\n      // either we didn't abort, and are still here, or we did, and ignored\n      const bf = p as BackgroundFetch\n      // if nothing else has been written there but we're set to update the\n      // cache and ignore the abort, or if it's still pending on this specific\n      // background request, then write it to the cache.\n      const vl = this.#valList[index as Index]\n      if (vl === p || (vl === undefined && ignoreAbort && updateCache)) {\n        if (v === undefined) {\n          if (bf.__staleWhileFetching !== undefined) {\n            this.#valList[index as Index] = bf.__staleWhileFetching\n          } else {\n            this.#delete(k, 'fetch')\n          }\n        } else {\n          if (options.status) options.status.fetchUpdated = true\n          this.#set(k, v, fetchOpts.options, bf)\n        }\n      }\n      return v\n    }\n\n    const eb = (er: unknown) => {\n      if (options.status) {\n        options.status.fetchRejected = true\n        options.status.fetchError = er as Error\n      }\n      // do not pass go, do not collect $200\n      return fetchFail(er, false)\n    }\n\n    const fetchFail = (er: unknown, proceed: boolean): V | undefined => {\n      const { aborted } = ac.signal\n      const allowStaleAborted = aborted && options.allowStaleOnFetchAbort\n      const allowStale =\n        allowStaleAborted || options.allowStaleOnFetchRejection\n      const noDelete = allowStale || options.noDeleteOnFetchRejection\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        // if we allow stale on fetch rejections, then we need to ensure that\n        // the stale value is not removed from the cache when the fetch fails.\n        const del =\n          !noDelete || (!proceed && bf.__staleWhileFetching === undefined)\n        if (del) {\n          this.#delete(k, 'fetch')\n        } else if (!allowStaleAborted) {\n          // still replace the *promise* with the stale value,\n          // since we are done with the promise at this point.\n          // leave it untouched if we're still waiting for an\n          // aborted background fetch that hasn't yet returned.\n          this.#valList[index as Index] = bf.__staleWhileFetching\n        }\n      }\n      if (allowStale) {\n        if (options.status && bf.__staleWhileFetching !== undefined) {\n          options.status.returnedStale = true\n        }\n        return bf.__staleWhileFetching\n      } else if (bf.__returned === bf) {\n        throw er\n      }\n    }\n\n    const pcall = (\n      res: (v: V | undefined) => void,\n      rej: (e: unknown) => void,\n    ) => {\n      const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n      // ignored, we go until we finish, regardless.\n      // defer check until we are actually aborting,\n      // so fetchMethod can override.\n      ac.signal.addEventListener('abort', () => {\n        if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {\n          res(undefined)\n          // when it eventually resolves, update the cache.\n          if (options.allowStaleOnFetchAbort) {\n            res = v => cb(v, true)\n          }\n        }\n      })\n      if (fmp && fmp instanceof Promise) {\n        fmp.then(v => res(v === undefined ? undefined : v), rej)\n      } else if (fmp !== undefined) {\n        res(fmp)\n      }\n    }\n\n    if (options.status) options.status.fetchDispatched = true\n    const p = new Promise(pcall).then(cb, eb)\n    const bf: BackgroundFetch = Object.assign(p, {\n      __abortController: ac,\n      __staleWhileFetching: v,\n      __returned: undefined,\n    })\n\n    if (index === undefined) {\n      // internal, don't expose status.\n      this.#set(k, bf, { ...fetchOpts.options, status: undefined })\n      index = this.#keyMap.get(k)\n    } else {\n      // do not call #set, because we do not want to adjust its place\n      // in the lru queue, as it has not yet been \"used\". Also, we don't\n      // need to worry about evicting for size, because a background fetch\n      // over a stale value is treated as the same size as its stale value.\n      this.#valList[index] = bf\n    }\n    return bf\n  }\n\n  #isBackgroundFetch(p: unknown): p is BackgroundFetch {\n    if (!this.#hasFetchMethod) return false\n    const b = p as BackgroundFetch\n    return (\n      !!b &&\n      b instanceof Promise &&\n      b.hasOwnProperty('__staleWhileFetching') &&\n      b.__abortController instanceof AbortController\n    )\n  }\n\n  /**\n   * Make an asynchronous cached fetch using the\n   * {@link LRUCache.OptionsBase.fetchMethod} function.\n   *\n   * If the value is in the cache and not stale, then the returned\n   * Promise resolves to the value.\n   *\n   * If not in the cache, or beyond its TTL staleness, then\n   * `fetchMethod(key, staleValue, { options, signal, context })` is\n   * called, and the value returned will be added to the cache once\n   * resolved.\n   *\n   * If called with `allowStale`, and an asynchronous fetch is\n   * currently in progress to reload a stale value, then the former\n   * stale value will be returned.\n   *\n   * If called with `forceRefresh`, then the cached item will be\n   * re-fetched, even if it is not stale. However, if `allowStale` is also\n   * set, then the old value will still be returned. This is useful\n   * in cases where you want to force a reload of a cached value. If\n   * a background fetch is already in progress, then `forceRefresh`\n   * has no effect.\n   *\n   * If multiple fetches for the same key are issued, then they will all be\n   * coalesced into a single call to fetchMethod.\n   *\n   * Note that this means that handling options such as\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n   * {@link LRUCache.FetchOptions.signal},\n   * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n   * determined by the FIRST fetch() call for a given key.\n   *\n   * This is a known (fixable) shortcoming which will be addresed on when\n   * someone complains about it, as the fix would involve added complexity and\n   * may not be worth the costs for this edge case.\n   *\n   * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n   * effectively an alias for `Promise.resolve(cache.get(key))`.\n   *\n   * When the fetch method resolves to a value, if the fetch has not\n   * been aborted due to deletion, eviction, or being overwritten,\n   * then it is added to the cache using the options provided.\n   *\n   * If the key is evicted or deleted before the `fetchMethod`\n   * resolves, then the AbortSignal passed to the `fetchMethod` will\n   * receive an `abort` event, and the promise returned by `fetch()`\n   * will reject with the reason for the abort.\n   *\n   * If a `signal` is passed to the `fetch()` call, then aborting the\n   * signal will abort the fetch and cause the `fetch()` promise to\n   * reject with the reason provided.\n   *\n   * **Setting `context`**\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the {@link LRUCache} constructor, then all\n   * calls to `cache.fetch()` _must_ provide a `context` option. If\n   * set to `undefined` or `void`, then calls to fetch _must not_\n   * provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that\n   * might be relevant in the course of fetching the data. It is only\n   * relevant for the course of a single `fetch()` operation, and\n   * discarded afterwards.\n   *\n   * **Note: `fetch()` calls are inflight-unique**\n   *\n   * If you call `fetch()` multiple times with the same key value,\n   * then every call after the first will resolve on the same\n   * promise1,\n   * _even if they have different settings that would otherwise change\n   * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n   * or `ignoreFetchAbort`.\n   *\n   * In most cases, this is not a problem (in fact, only fetching\n   * something once is what you probably want, if you're caching in\n   * the first place). If you are changing the fetch() options\n   * dramatically between runs, there's a good chance that you might\n   * be trying to fit divergent semantics into a single object, and\n   * would be better off with multiple cache instances.\n   *\n   * **1**: Ie, they're not the \"same Promise\", but they resolve at\n   * the same time, because they're both waiting on the same\n   * underlying fetchMethod response.\n   */\n\n  fetch(\n    k: K,\n    fetchOptions: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ?\n      LRUCache.FetchOptionsNoContext\n    : LRUCache.FetchOptionsWithContext,\n  ): Promise\n\n  // this overload not allowed if context is required\n  fetch(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    fetchOptions?: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ?\n      LRUCache.FetchOptionsNoContext\n    : never,\n  ): Promise\n  fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const ths = tracing.hasSubscribers\n    const { status = hasSubscribers() ? {} : undefined } = fetchOptions\n    fetchOptions.status = status\n    if (status && fetchOptions.context) {\n      status.context = fetchOptions.context\n    }\n    const p = this.#fetch(k, fetchOptions)\n    if (status && ths) {\n      status.trace = true\n      tracing.tracePromise(() => p, status).catch(() => {})\n    }\n    return p\n  }\n\n  async #fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const {\n      // get options\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      // set options\n      ttl = this.ttl,\n      noDisposeOnSet = this.noDisposeOnSet,\n      size = 0,\n      sizeCalculation = this.sizeCalculation,\n      noUpdateTTL = this.noUpdateTTL,\n      // fetch exclusive options\n      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n      ignoreFetchAbort = this.ignoreFetchAbort,\n      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n      context,\n      forceRefresh = false,\n      status,\n      signal,\n    } = fetchOptions\n    if (status) {\n      status.op = 'fetch'\n      status.key = k\n      if (forceRefresh) status.forceRefresh = true\n      status.cache = this\n    }\n\n    if (!this.#hasFetchMethod) {\n      if (status) status.fetch = 'get'\n      return this.#get(k, {\n        allowStale,\n        updateAgeOnGet,\n        noDeleteOnStaleGet,\n        status,\n      })\n    }\n\n    const options = {\n      allowStale,\n      updateAgeOnGet,\n      noDeleteOnStaleGet,\n      ttl,\n      noDisposeOnSet,\n      size,\n      sizeCalculation,\n      noUpdateTTL,\n      noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      status,\n      signal,\n    }\n\n    let index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.fetch = 'miss'\n      const p = this.#backgroundFetch(k, index, options, context as FC)\n      return (p.__returned = p)\n    } else {\n      // in cache, maybe already fetching\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        const stale = allowStale && v.__staleWhileFetching !== undefined\n        if (status) {\n          status.fetch = 'inflight'\n          if (stale) status.returnedStale = true\n        }\n        return stale ? v.__staleWhileFetching : (v.__returned = v)\n      }\n\n      // if we force a refresh, that means do NOT serve the cached value,\n      // unless we are already in the process of refreshing the cache.\n      const isStale = this.#isStale(index)\n      if (!forceRefresh && !isStale) {\n        if (status) status.fetch = 'hit'\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        if (status) this.#statusTTL(status, index)\n        return v\n      }\n\n      // ok, it is stale or a forced refresh, and not already fetching.\n      // refresh the cache.\n      const p = this.#backgroundFetch(k, index, options, context as FC)\n      const hasStale = p.__staleWhileFetching !== undefined\n      const staleVal = hasStale && allowStale\n      if (status) {\n        status.fetch = isStale ? 'stale' : 'refresh'\n        if (staleVal && isStale) status.returnedStale = true\n      }\n      return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n    }\n  }\n\n  /**\n   * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n   * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n   * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n   * because `ignoreFetchAbort` was specified (either to the constructor or\n   * in the {@link LRUCache.FetchOptions}). Also, the\n   * {@link LRUCache.OptionsBase.fetchMethod} may return `undefined` or `void`, making\n   * the test even more complicated.\n   *\n   * Because inferring the cases where `undefined` might be returned are so\n   * cumbersome, but testing for `undefined` can also be annoying, this method\n   * can be used, which will reject if `this.fetch()` resolves to undefined.\n   */\n  forceFetch(\n    k: K,\n    fetchOptions: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ?\n      LRUCache.FetchOptionsNoContext\n    : LRUCache.FetchOptionsWithContext,\n  ): Promise\n  // this overload not allowed if context is required\n  forceFetch(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    fetchOptions?: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ?\n      LRUCache.FetchOptionsNoContext\n    : never,\n  ): Promise\n  forceFetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const ths = tracing.hasSubscribers\n    const { status = hasSubscribers() ? {} : undefined } = fetchOptions\n    fetchOptions.status = status\n    if (status && fetchOptions.context) {\n      status.context = fetchOptions.context\n    }\n    const p = this.#forceFetch(k, fetchOptions)\n    if (status && ths) {\n      status.trace = true\n      tracing.tracePromise(() => p, status).catch(() => {})\n    }\n    return p\n  }\n\n  async #forceFetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ) {\n    const v = await this.#fetch(k, fetchOptions)\n    if (v === undefined) throw new Error('fetch() returned undefined')\n    return v\n  }\n\n  /**\n   * If the key is found in the cache, then this is equivalent to\n   * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n   * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n   * _must_ provide a `context` option. If set to `undefined` or `void`, then\n   * calls to memo _must not_ provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that might be\n   * relevant in the course of fetching the data. It is only relevant for the\n   * course of a single `memo()` operation, and discarded afterwards.\n   */\n  memo(\n    k: K,\n    memoOptions: unknown extends FC ? LRUCache.MemoOptions\n    : FC extends undefined | void ? LRUCache.MemoOptionsNoContext\n    : LRUCache.MemoOptionsWithContext,\n  ): V\n  // this overload not allowed if context is required\n  memo(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    memoOptions?: unknown extends FC ? LRUCache.MemoOptions\n    : FC extends undefined | void ? LRUCache.MemoOptionsNoContext\n    : never,\n  ): V\n  memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n    const { status = metrics.hasSubscribers ? {} : undefined } =\n      memoOptions\n    memoOptions.status = status\n    if (status) {\n      status.op = 'memo'\n      status.key = k\n      if (memoOptions.context) {\n        status.context = memoOptions.context\n      }\n      status.cache = this\n    }\n    const result = this.#memo(k, memoOptions)\n    if (status) status.value = result\n    if (metrics.hasSubscribers) metrics.publish(status)\n    return result\n  }\n  #memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n    const memoMethod = this.#memoMethod\n    if (!memoMethod) {\n      throw new Error('no memoMethod provided to constructor')\n    }\n    const { context, status, forceRefresh, ...options } = memoOptions\n    if (status && forceRefresh) status.forceRefresh = true\n    const v = this.#get(k, options)\n    const refresh = forceRefresh || v === undefined\n    if (status) {\n      status.memo = refresh ? 'miss' : 'hit'\n      if (!refresh) status.value = v\n    }\n    if (!refresh) return v\n    const vv = memoMethod(k, v, {\n      options,\n      context,\n    } as LRUCache.MemoizerOptions)\n    if (status) status.value = vv\n    this.#set(k, vv, options)\n    return vv\n  }\n\n  /**\n   * Return a value from the cache. Will update the recency of the cache\n   * entry found.\n   *\n   * If the key is not found, get() will return `undefined`.\n   */\n  get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const { status = metrics.hasSubscribers ? {} : undefined } = getOptions\n    getOptions.status = status\n    if (status) {\n      status.op = 'get'\n      status.key = k\n      status.cache = this\n    }\n    const result = this.#get(k, getOptions)\n    if (status) {\n      if (result !== undefined) status.value = result\n      if (metrics.hasSubscribers) metrics.publish(status)\n    }\n    return result\n  }\n\n  #get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const {\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      status,\n    } = getOptions\n    const index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.get = 'miss'\n      return undefined\n    }\n    const value = this.#valList[index]\n    const fetching = this.#isBackgroundFetch(value)\n    if (status) this.#statusTTL(status, index)\n    if (this.#isStale(index)) {\n      // delete only if not an in-flight background fetch\n      if (!fetching) {\n        if (!noDeleteOnStaleGet) {\n          this.#delete(k, 'expire')\n        }\n        if (status) status.get = 'stale'\n        if (allowStale) {\n          if (status) status.returnedStale = true\n          return value\n        }\n        return undefined\n      }\n      if (status) status.get = 'stale-fetching'\n      if (allowStale && value.__staleWhileFetching !== undefined) {\n        if (status) status.returnedStale = true\n        return value.__staleWhileFetching\n      }\n      return undefined\n    }\n    // not stale\n    if (status) status.get = fetching ? 'fetching' : 'hit'\n    // if we're currently fetching it, we don't actually have it yet\n    // it's not stale, which means this isn't a staleWhileRefetching.\n    // If it's not stale, and fetching, AND has a __staleWhileFetching\n    // value, then that means the user fetched with {forceRefresh:true},\n    // so it's safe to return that value.\n    this.#moveToTail(index)\n    if (updateAgeOnGet) {\n      this.#updateItemAge(index)\n    }\n    return fetching ? value.__staleWhileFetching : value\n  }\n\n  #connect(p: Index, n: Index) {\n    this.#prev[n] = p\n    this.#next[p] = n\n  }\n\n  #moveToTail(index: Index): void {\n    // if tail already, nothing to do\n    // if head, move head to next[index]\n    // else\n    //   move next[prev[index]] to next[index] (head has no prev)\n    //   move prev[next[index]] to prev[index]\n    // prev[index] = tail\n    // next[tail] = index\n    // tail = index\n    if (index !== this.#tail) {\n      if (index === this.#head) {\n        this.#head = this.#next[index] as Index\n      } else {\n        this.#connect(\n          this.#prev[index] as Index,\n          this.#next[index] as Index,\n        )\n      }\n      this.#connect(this.#tail, index)\n      this.#tail = index\n    }\n  }\n\n  /**\n   * Deletes a key out of the cache.\n   *\n   * Returns true if the key was deleted, false otherwise.\n   */\n  delete(k: K) {\n    return this.#delete(k, 'delete')\n  }\n\n  #delete(k: K, reason: LRUCache.DisposeReason) {\n    if (metrics.hasSubscribers) {\n      metrics.publish({\n        op: 'delete',\n        delete: reason,\n        key: k,\n        cache: this,\n      })\n    }\n    let deleted = false\n    if (this.#size !== 0) {\n      const index = this.#keyMap.get(k)\n      if (index !== undefined) {\n        if (this.#autopurgeTimers?.[index]) {\n          clearTimeout(this.#autopurgeTimers[index])\n          this.#autopurgeTimers[index] = undefined\n        }\n        deleted = true\n        if (this.#size === 1) {\n          this.#clear(reason)\n        } else {\n          this.#removeItemSize(index)\n          const v = this.#valList[index]\n          if (this.#isBackgroundFetch(v)) {\n            v.__abortController.abort(new Error('deleted'))\n          } else if (this.#hasDispose || this.#hasDisposeAfter) {\n            if (this.#hasDispose) {\n              this.#dispose?.(v as V, k, reason)\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([v as V, k, reason])\n            }\n          }\n          this.#keyMap.delete(k)\n          this.#keyList[index] = undefined\n          this.#valList[index] = undefined\n          if (index === this.#tail) {\n            this.#tail = this.#prev[index] as Index\n          } else if (index === this.#head) {\n            this.#head = this.#next[index] as Index\n          } else {\n            const pi = this.#prev[index] as number\n            this.#next[pi] = this.#next[index] as number\n            const ni = this.#next[index] as number\n            this.#prev[ni] = this.#prev[index] as number\n          }\n          this.#size--\n          this.#free.push(index)\n        }\n      }\n    }\n    if (this.#hasDisposeAfter && this.#disposed?.length) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Clear the cache entirely, throwing away all values.\n   */\n  clear() {\n    return this.#clear('delete')\n  }\n  #clear(reason: LRUCache.DisposeReason) {\n    for (const index of this.#rindexes({ allowStale: true })) {\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        v.__abortController.abort(new Error('deleted'))\n      } else {\n        const k = this.#keyList[index]\n        if (this.#hasDispose) {\n          this.#dispose?.(v as V, k as K, reason)\n        }\n        if (this.#hasDisposeAfter) {\n          this.#disposed?.push([v as V, k as K, reason])\n        }\n      }\n    }\n\n    this.#keyMap.clear()\n    void this.#valList.fill(undefined)\n    this.#keyList.fill(undefined)\n    if (this.#ttls && this.#starts) {\n      this.#ttls.fill(0)\n      this.#starts.fill(0)\n      for (const t of this.#autopurgeTimers ?? []) {\n        if (t !== undefined) clearTimeout(t)\n      }\n      this.#autopurgeTimers?.fill(undefined)\n    }\n    if (this.#sizes) {\n      this.#sizes.fill(0)\n    }\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free.length = 0\n    this.#calculatedSize = 0\n    this.#size = 0\n    if (this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n  }\n}\n", "const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n  s: any\n): s is Minipass.Readable | Minipass.Writable =>\n  !!s &&\n  typeof s === 'object' &&\n  (s instanceof Minipass ||\n    s instanceof Stream ||\n    isReadable(s) ||\n    isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Readable).pipe === 'function' &&\n  // node core Writable streams have a pipe() method, but it throws\n  (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Writable).write === 'function' &&\n  typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n  ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n  b instanceof ArrayBuffer ||\n  (!!b &&\n    typeof b === 'object' &&\n    b.constructor &&\n    b.constructor.name === 'ArrayBuffer' &&\n    b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n  !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n  /**\n   * end the destination stream when the source stream ends\n   */\n  end?: boolean\n  /**\n   * proxy errors from the source stream to the destination stream\n   */\n  proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n  src: Minipass\n  dest: Minipass\n  opts: PipeOptions\n  ondrain: () => any\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    this.src = src\n    this.dest = dest as Minipass\n    this.opts = opts\n    this.ondrain = () => src[RESUME]()\n    this.dest.on('drain', this.ondrain)\n  }\n  unpipe() {\n    this.dest.removeListener('drain', this.ondrain)\n  }\n  // only here for the prototype\n  /* c8 ignore start */\n  proxyErrors(_er: any) {}\n  /* c8 ignore stop */\n  end() {\n    this.unpipe()\n    if (this.opts.end) this.dest.end()\n  }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n  unpipe() {\n    this.src.removeListener('error', this.proxyErrors)\n    super.unpipe()\n  }\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    super(src, dest, opts)\n    this.proxyErrors = (er: Error) => this.dest.emit('error', er)\n    src.on('error', this.proxyErrors)\n  }\n}\n\nexport namespace Minipass {\n  /**\n   * Encoding used to create a stream that outputs strings rather than\n   * Buffer objects.\n   */\n  export type Encoding = BufferEncoding | 'buffer' | null\n\n  /**\n   * Any stream that Minipass can pipe into\n   */\n  export type Writable =\n    | Minipass\n    | NodeJS.WriteStream\n    | (NodeJS.WriteStream & { fd: number })\n    | (EventEmitter & {\n        end(): any\n        write(chunk: any, ...args: any[]): any\n      })\n\n  /**\n   * Any stream that can be read from\n   */\n  export type Readable =\n    | Minipass\n    | NodeJS.ReadStream\n    | (NodeJS.ReadStream & { fd: number })\n    | (EventEmitter & {\n        pause(): any\n        resume(): any\n        pipe(...destArgs: any[]): any\n      })\n\n  /**\n   * Utility type that can be iterated sync or async\n   */\n  export type DualIterable = Iterable & AsyncIterable\n\n  type EventArguments = Record\n\n  /**\n   * The listing of events that a Minipass class can emit.\n   * Extend this when extending the Minipass class, and pass as\n   * the third template argument.  The key is the name of the event,\n   * and the value is the argument list.\n   *\n   * Any undeclared events will still be allowed, but the handler will get\n   * arguments as `unknown[]`.\n   */\n  export interface Events\n    extends EventArguments {\n    readable: []\n    data: [chunk: RType]\n    error: [er: unknown]\n    abort: [reason: unknown]\n    drain: []\n    resume: []\n    end: []\n    finish: []\n    prefinish: []\n    close: []\n    [DESTROYED]: [er?: unknown]\n    [ERROR]: [er: unknown]\n  }\n\n  /**\n   * String or buffer-like data that can be joined and sliced\n   */\n  export type ContiguousData =\n    | Buffer\n    | ArrayBufferLike\n    | ArrayBufferView\n    | string\n  export type BufferOrString = Buffer | string\n\n  /**\n   * Options passed to the Minipass constructor.\n   */\n  export type SharedOptions = {\n    /**\n     * Defer all data emission and other events until the end of the\n     * current tick, similar to Node core streams\n     */\n    async?: boolean\n    /**\n     * A signal which will abort the stream\n     */\n    signal?: AbortSignal\n    /**\n     * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n     * emit Buffer objects rather than strings.\n     *\n     * Conflicts with `objectMode`\n     */\n    encoding?: BufferEncoding | null | 'buffer'\n    /**\n     * Output data exactly as it was written, supporting non-buffer/string\n     * data (such as arbitrary objects, falsey values, etc.)\n     *\n     * Conflicts with `encoding`\n     */\n    objectMode?: boolean\n  }\n\n  /**\n   * Options for a string encoded output\n   */\n  export type EncodingOptions = SharedOptions & {\n    encoding: BufferEncoding\n    objectMode?: false\n  }\n\n  /**\n   * Options for contiguous data buffer output\n   */\n  export type BufferOptions = SharedOptions & {\n    encoding?: null | 'buffer'\n    objectMode?: false\n  }\n\n  /**\n   * Options for objectMode arbitrary output\n   */\n  export type ObjectModeOptions = SharedOptions & {\n    objectMode: true\n    encoding?: null\n  }\n\n  /**\n   * Utility type to determine allowed options based on read type\n   */\n  export type Options =\n    | ObjectModeOptions\n    | (T extends string\n        ? EncodingOptions\n        : T extends Buffer\n        ? BufferOptions\n        : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n  !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n    RType extends unknown = Buffer,\n    WType extends unknown = RType extends Minipass.BufferOrString\n      ? Minipass.ContiguousData\n      : RType,\n    Events extends Minipass.Events = Minipass.Events\n  >\n  extends EventEmitter\n  implements Minipass.DualIterable\n{\n  [FLOWING]: boolean = false;\n  [PAUSED]: boolean = false;\n  [PIPES]: Pipe[] = [];\n  [BUFFER]: RType[] = [];\n  [OBJECTMODE]: boolean;\n  [ENCODING]: BufferEncoding | null;\n  [ASYNC]: boolean;\n  [DECODER]: SD | null;\n  [EOF]: boolean = false;\n  [EMITTED_END]: boolean = false;\n  [EMITTING_END]: boolean = false;\n  [CLOSED]: boolean = false;\n  [EMITTED_ERROR]: unknown = null;\n  [BUFFERLENGTH]: number = 0;\n  [DESTROYED]: boolean = false;\n  [SIGNAL]?: AbortSignal;\n  [ABORTED]: boolean = false;\n  [DATALISTENERS]: number = 0;\n  [DISCARDED]: boolean = false\n\n  /**\n   * true if the stream can be written\n   */\n  writable: boolean = true\n  /**\n   * true if the stream can be read\n   */\n  readable: boolean = true\n\n  /**\n   * If `RType` is Buffer, then options do not need to be provided.\n   * Otherwise, an options object must be provided to specify either\n   * {@link Minipass.SharedOptions.objectMode} or\n   * {@link Minipass.SharedOptions.encoding}, as appropriate.\n   */\n  constructor(\n    ...args:\n      | [Minipass.ObjectModeOptions]\n      | (RType extends Buffer\n          ? [] | [Minipass.Options]\n          : [Minipass.Options])\n  ) {\n    const options: Minipass.Options = (args[0] ||\n      {}) as Minipass.Options\n    super()\n    if (options.objectMode && typeof options.encoding === 'string') {\n      throw new TypeError(\n        'Encoding and objectMode may not be used together'\n      )\n    }\n    if (isObjectModeOptions(options)) {\n      this[OBJECTMODE] = true\n      this[ENCODING] = null\n    } else if (isEncodingOptions(options)) {\n      this[ENCODING] = options.encoding\n      this[OBJECTMODE] = false\n    } else {\n      this[OBJECTMODE] = false\n      this[ENCODING] = null\n    }\n    this[ASYNC] = !!options.async\n    this[DECODER] = this[ENCODING]\n      ? (new StringDecoder(this[ENCODING]) as SD)\n      : null\n\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposeBuffer === true) {\n      Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n    }\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposePipes === true) {\n      Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n    }\n\n    const { signal } = options\n    if (signal) {\n      this[SIGNAL] = signal\n      if (signal.aborted) {\n        this[ABORT]()\n      } else {\n        signal.addEventListener('abort', () => this[ABORT]())\n      }\n    }\n  }\n\n  /**\n   * The amount of data stored in the buffer waiting to be read.\n   *\n   * For Buffer strings, this will be the total byte length.\n   * For string encoding streams, this will be the string character length,\n   * according to JavaScript's `string.length` logic.\n   * For objectMode streams, this is a count of the items waiting to be\n   * emitted.\n   */\n  get bufferLength() {\n    return this[BUFFERLENGTH]\n  }\n\n  /**\n   * The `BufferEncoding` currently in use, or `null`\n   */\n  get encoding() {\n    return this[ENCODING]\n  }\n\n  /**\n   * @deprecated - This is a read only property\n   */\n  set encoding(_enc) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * @deprecated - Encoding may only be set at instantiation time\n   */\n  setEncoding(_enc: Minipass.Encoding) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * True if this is an objectMode stream\n   */\n  get objectMode() {\n    return this[OBJECTMODE]\n  }\n\n  /**\n   * @deprecated - This is a read-only property\n   */\n  set objectMode(_om) {\n    throw new Error('objectMode must be set at instantiation time')\n  }\n\n  /**\n   * true if this is an async stream\n   */\n  get ['async'](): boolean {\n    return this[ASYNC]\n  }\n  /**\n   * Set to true to make this stream async.\n   *\n   * Once set, it cannot be unset, as this would potentially cause incorrect\n   * behavior.  Ie, a sync stream can be made async, but an async stream\n   * cannot be safely made sync.\n   */\n  set ['async'](a: boolean) {\n    this[ASYNC] = this[ASYNC] || !!a\n  }\n\n  // drop everything and get out of the flow completely\n  [ABORT]() {\n    this[ABORTED] = true\n    this.emit('abort', this[SIGNAL]?.reason)\n    this.destroy(this[SIGNAL]?.reason)\n  }\n\n  /**\n   * True if the stream has been aborted.\n   */\n  get aborted() {\n    return this[ABORTED]\n  }\n  /**\n   * No-op setter. Stream aborted status is set via the AbortSignal provided\n   * in the constructor options.\n   */\n  set aborted(_) {}\n\n  /**\n   * Write data into the stream\n   *\n   * If the chunk written is a string, and encoding is not specified, then\n   * `utf8` will be assumed. If the stream encoding matches the encoding of\n   * a written string, and the state of the string decoder allows it, then\n   * the string will be passed through to either the output or the internal\n   * buffer without any processing. Otherwise, it will be turned into a\n   * Buffer object for processing into the desired encoding.\n   *\n   * If provided, `cb` function is called immediately before return for\n   * sync streams, or on next tick for async streams, because for this\n   * base class, a chunk is considered \"processed\" once it is accepted\n   * and either emitted or buffered. That is, the callback does not indicate\n   * that the chunk has been eventually emitted, though of course child\n   * classes can override this function to do whatever processing is required\n   * and call `super.write(...)` only once processing is completed.\n   */\n  write(chunk: WType, cb?: () => void): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding,\n    cb?: () => void\n  ): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): boolean {\n    if (this[ABORTED]) return false\n    if (this[EOF]) throw new Error('write after end')\n\n    if (this[DESTROYED]) {\n      this.emit(\n        'error',\n        Object.assign(\n          new Error('Cannot call write after a stream was destroyed'),\n          { code: 'ERR_STREAM_DESTROYED' }\n        )\n      )\n      return true\n    }\n\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n\n    if (!encoding) encoding = 'utf8'\n\n    const fn = this[ASYNC] ? defer : nodefer\n\n    // convert array buffers and typed array views into buffers\n    // at some point in the future, we may want to do the opposite!\n    // leave strings and buffers as-is\n    // anything is only allowed if in object mode, so throw\n    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n      if (isArrayBufferView(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(\n          chunk.buffer,\n          chunk.byteOffset,\n          chunk.byteLength\n        )\n      } else if (isArrayBufferLike(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(chunk)\n      } else if (typeof chunk !== 'string') {\n        throw new Error(\n          'Non-contiguous data written to non-objectMode stream'\n        )\n      }\n    }\n\n    // handle object mode up front, since it's simpler\n    // this yields better performance, fewer checks later.\n    if (this[OBJECTMODE]) {\n      // maybe impossible?\n      /* c8 ignore start */\n      if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n      /* c8 ignore stop */\n\n      if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n      else this[BUFFERPUSH](chunk as unknown as RType)\n\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n      if (cb) fn(cb)\n\n      return this[FLOWING]\n    }\n\n    // at this point the chunk is a buffer or string\n    // don't buffer it up or send it to the decoder\n    if (!(chunk as Minipass.BufferOrString).length) {\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n      if (cb) fn(cb)\n      return this[FLOWING]\n    }\n\n    // fast-path writing strings of same encoding to a stream with\n    // an empty buffer, skipping the buffer/decoder dance\n    if (\n      typeof chunk === 'string' &&\n      // unless it is a string already ready for us to use\n      !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n    ) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = Buffer.from(chunk, encoding)\n    }\n\n    if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = this[DECODER].write(chunk)\n    }\n\n    // Note: flushing CAN potentially switch us into not-flowing mode\n    if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n    if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n    else this[BUFFERPUSH](chunk as unknown as RType)\n\n    if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n    if (cb) fn(cb)\n\n    return this[FLOWING]\n  }\n\n  /**\n   * Low-level explicit read method.\n   *\n   * In objectMode, the argument is ignored, and one item is returned if\n   * available.\n   *\n   * `n` is the number of bytes (or in the case of encoding streams,\n   * characters) to consume. If `n` is not provided, then the entire buffer\n   * is returned, or `null` is returned if no data is available.\n   *\n   * If `n` is greater that the amount of data in the internal buffer,\n   * then `null` is returned.\n   */\n  read(n?: number | null): RType | null {\n    if (this[DESTROYED]) return null\n    this[DISCARDED] = false\n\n    if (\n      this[BUFFERLENGTH] === 0 ||\n      n === 0 ||\n      (n && n > this[BUFFERLENGTH])\n    ) {\n      this[MAYBE_EMIT_END]()\n      return null\n    }\n\n    if (this[OBJECTMODE]) n = null\n\n    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n      // not object mode, so if we have an encoding, then RType is string\n      // otherwise, must be Buffer\n      this[BUFFER] = [\n        (this[ENCODING]\n          ? this[BUFFER].join('')\n          : Buffer.concat(\n              this[BUFFER] as Buffer[],\n              this[BUFFERLENGTH]\n            )) as RType,\n      ]\n    }\n\n    const ret = this[READ](n || null, this[BUFFER][0] as RType)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [READ](n: number | null, chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n    else {\n      const c = chunk as Minipass.BufferOrString\n      if (n === c.length || n === null) this[BUFFERSHIFT]()\n      else if (typeof c === 'string') {\n        this[BUFFER][0] = c.slice(n) as RType\n        chunk = c.slice(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      } else {\n        this[BUFFER][0] = c.subarray(n) as RType\n        chunk = c.subarray(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      }\n    }\n\n    this.emit('data', chunk)\n\n    if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n    return chunk\n  }\n\n  /**\n   * End the stream, optionally providing a final write.\n   *\n   * See {@link Minipass#write} for argument descriptions\n   */\n  end(cb?: () => void): this\n  end(chunk: WType, cb?: () => void): this\n  end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n  end(\n    chunk?: WType | (() => void),\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): this {\n    if (typeof chunk === 'function') {\n      cb = chunk as () => void\n      chunk = undefined\n    }\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n    if (chunk !== undefined) this.write(chunk, encoding)\n    if (cb) this.once('end', cb)\n    this[EOF] = true\n    this.writable = false\n\n    // if we haven't written anything, then go ahead and emit,\n    // even if we're not reading.\n    // we'll re-emit if a new 'end' listener is added anyway.\n    // This makes MP more suitable to write-only use cases.\n    if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n    return this\n  }\n\n  // don't let the internal resume be overwritten\n  [RESUME]() {\n    if (this[DESTROYED]) return\n\n    if (!this[DATALISTENERS] && !this[PIPES].length) {\n      this[DISCARDED] = true\n    }\n    this[PAUSED] = false\n    this[FLOWING] = true\n    this.emit('resume')\n    if (this[BUFFER].length) this[FLUSH]()\n    else if (this[EOF]) this[MAYBE_EMIT_END]()\n    else this.emit('drain')\n  }\n\n  /**\n   * Resume the stream if it is currently in a paused state\n   *\n   * If called when there are no pipe destinations or `data` event listeners,\n   * this will place the stream in a \"discarded\" state, where all data will\n   * be thrown away. The discarded state is removed if a pipe destination or\n   * data handler is added, if pause() is called, or if any synchronous or\n   * asynchronous iteration is started.\n   */\n  resume() {\n    return this[RESUME]()\n  }\n\n  /**\n   * Pause the stream\n   */\n  pause() {\n    this[FLOWING] = false\n    this[PAUSED] = true\n    this[DISCARDED] = false\n  }\n\n  /**\n   * true if the stream has been forcibly destroyed\n   */\n  get destroyed() {\n    return this[DESTROYED]\n  }\n\n  /**\n   * true if the stream is currently in a flowing state, meaning that\n   * any writes will be immediately emitted.\n   */\n  get flowing() {\n    return this[FLOWING]\n  }\n\n  /**\n   * true if the stream is currently in a paused state\n   */\n  get paused() {\n    return this[PAUSED]\n  }\n\n  [BUFFERPUSH](chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n    else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n    this[BUFFER].push(chunk)\n  }\n\n  [BUFFERSHIFT](): RType {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n    else\n      this[BUFFERLENGTH] -= (\n        this[BUFFER][0] as Minipass.BufferOrString\n      ).length\n    return this[BUFFER].shift() as RType\n  }\n\n  [FLUSH](noDrain: boolean = false) {\n    do {} while (\n      this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n      this[BUFFER].length\n    )\n\n    if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n  }\n\n  [FLUSHCHUNK](chunk: RType) {\n    this.emit('data', chunk)\n    return this[FLOWING]\n  }\n\n  /**\n   * Pipe all data emitted by this stream into the destination provided.\n   *\n   * Triggers the flow of data.\n   */\n  pipe(dest: W, opts?: PipeOptions): W {\n    if (this[DESTROYED]) return dest\n    this[DISCARDED] = false\n\n    const ended = this[EMITTED_END]\n    opts = opts || {}\n    if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n    else opts.end = opts.end !== false\n    opts.proxyErrors = !!opts.proxyErrors\n\n    // piping an ended stream ends immediately\n    if (ended) {\n      if (opts.end) dest.end()\n    } else {\n      // \"as\" here just ignores the WType, which pipes don't care about,\n      // since they're only consuming from us, and writing to the dest\n      this[PIPES].push(\n        !opts.proxyErrors\n          ? new Pipe(this as Minipass, dest, opts)\n          : new PipeProxyErrors(this as Minipass, dest, opts)\n      )\n      if (this[ASYNC]) defer(() => this[RESUME]())\n      else this[RESUME]()\n    }\n\n    return dest\n  }\n\n  /**\n   * Fully unhook a piped destination stream.\n   *\n   * If the destination stream was the only consumer of this stream (ie,\n   * there are no other piped destinations or `'data'` event listeners)\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  unpipe(dest: W) {\n    const p = this[PIPES].find(p => p.dest === dest)\n    if (p) {\n      if (this[PIPES].length === 1) {\n        if (this[FLOWING] && this[DATALISTENERS] === 0) {\n          this[FLOWING] = false\n        }\n        this[PIPES] = []\n      } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n      p.unpipe()\n    }\n  }\n\n  /**\n   * Alias for {@link Minipass#on}\n   */\n  addListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    return this.on(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.on`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * - Adding a 'data' event handler will trigger the flow of data\n   *\n   * - Adding a 'readable' event handler when there is data waiting to be read\n   *   will cause 'readable' to be emitted immediately.\n   *\n   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n   *   already passed will cause the event to be emitted immediately and all\n   *   handlers removed.\n   *\n   * - Adding an 'error' event handler after an error has been emitted will\n   *   cause the event to be re-emitted immediately with the error previously\n   *   raised.\n   */\n  on(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    const ret = super.on(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    if (ev === 'data') {\n      this[DISCARDED] = false\n      this[DATALISTENERS]++\n      if (!this[PIPES].length && !this[FLOWING]) {\n        this[RESUME]()\n      }\n    } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n      super.emit('readable')\n    } else if (isEndish(ev) && this[EMITTED_END]) {\n      super.emit(ev)\n      this.removeAllListeners(ev)\n    } else if (ev === 'error' && this[EMITTED_ERROR]) {\n      const h = handler as (...a: Events['error']) => any\n      if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n      else h.call(this, this[EMITTED_ERROR])\n    }\n    return ret\n  }\n\n  /**\n   * Alias for {@link Minipass#off}\n   */\n  removeListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    return this.off(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.off`\n   *\n   * If a 'data' event handler is removed, and it was the last consumer\n   * (ie, there are no pipe destinations or other 'data' event listeners),\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  off(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    const ret = super.off(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    // if we previously had listeners, and now we don't, and we don't\n    // have any pipes, then stop the flow, unless it's been explicitly\n    // put in a discarded flowing state via stream.resume().\n    if (ev === 'data') {\n      this[DATALISTENERS] = this.listeners('data').length\n      if (\n        this[DATALISTENERS] === 0 &&\n        !this[DISCARDED] &&\n        !this[PIPES].length\n      ) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.removeAllListeners`\n   *\n   * If all 'data' event handlers are removed, and they were the last consumer\n   * (ie, there are no pipe destinations), then the flow of data will stop\n   * until there is another consumer or {@link Minipass#resume} is explicitly\n   * called.\n   */\n  removeAllListeners(ev?: Event) {\n    const ret = super.removeAllListeners(ev as string | symbol | undefined)\n    if (ev === 'data' || ev === undefined) {\n      this[DATALISTENERS] = 0\n      if (!this[DISCARDED] && !this[PIPES].length) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * true if the 'end' event has been emitted\n   */\n  get emittedEnd() {\n    return this[EMITTED_END]\n  }\n\n  [MAYBE_EMIT_END]() {\n    if (\n      !this[EMITTING_END] &&\n      !this[EMITTED_END] &&\n      !this[DESTROYED] &&\n      this[BUFFER].length === 0 &&\n      this[EOF]\n    ) {\n      this[EMITTING_END] = true\n      this.emit('end')\n      this.emit('prefinish')\n      this.emit('finish')\n      if (this[CLOSED]) this.emit('close')\n      this[EMITTING_END] = false\n    }\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.emit`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * If the stream has been destroyed, and the event is something other\n   * than 'close' or 'error', then `false` is returned and no handlers\n   * are called.\n   *\n   * If the event is 'end', and has already been emitted, then the event\n   * is ignored. If the stream is in a paused or non-flowing state, then\n   * the event will be deferred until data flow resumes. If the stream is\n   * async, then handlers will be called on the next tick rather than\n   * immediately.\n   *\n   * If the event is 'close', and 'end' has not yet been emitted, then\n   * the event will be deferred until after 'end' is emitted.\n   *\n   * If the event is 'error', and an AbortSignal was provided for the stream,\n   * and there are no listeners, then the event is ignored, matching the\n   * behavior of node core streams in the presense of an AbortSignal.\n   *\n   * If the event is 'finish' or 'prefinish', then all listeners will be\n   * removed after emitting the event, to prevent double-firing.\n   */\n  emit(\n    ev: Event,\n    ...args: Events[Event]\n  ): boolean {\n    const data = args[0]\n    // error and close are only events allowed after calling destroy()\n    if (\n      ev !== 'error' &&\n      ev !== 'close' &&\n      ev !== DESTROYED &&\n      this[DESTROYED]\n    ) {\n      return false\n    } else if (ev === 'data') {\n      return !this[OBJECTMODE] && !data\n        ? false\n        : this[ASYNC]\n        ? (defer(() => this[EMITDATA](data as RType)), true)\n        : this[EMITDATA](data as RType)\n    } else if (ev === 'end') {\n      return this[EMITEND]()\n    } else if (ev === 'close') {\n      this[CLOSED] = true\n      // don't emit close before 'end' and 'finish'\n      if (!this[EMITTED_END] && !this[DESTROYED]) return false\n      const ret = super.emit('close')\n      this.removeAllListeners('close')\n      return ret\n    } else if (ev === 'error') {\n      this[EMITTED_ERROR] = data\n      super.emit(ERROR, data)\n      const ret =\n        !this[SIGNAL] || this.listeners('error').length\n          ? super.emit('error', data)\n          : false\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'resume') {\n      const ret = super.emit('resume')\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'finish' || ev === 'prefinish') {\n      const ret = super.emit(ev)\n      this.removeAllListeners(ev)\n      return ret\n    }\n\n    // Some other unknown event\n    const ret = super.emit(ev as string, ...args)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITDATA](data: RType) {\n    for (const p of this[PIPES]) {\n      if (p.dest.write(data as RType) === false) this.pause()\n    }\n    const ret = this[DISCARDED] ? false : super.emit('data', data)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITEND]() {\n    if (this[EMITTED_END]) return false\n\n    this[EMITTED_END] = true\n    this.readable = false\n    return this[ASYNC]\n      ? (defer(() => this[EMITEND2]()), true)\n      : this[EMITEND2]()\n  }\n\n  [EMITEND2]() {\n    if (this[DECODER]) {\n      const data = this[DECODER].end()\n      if (data) {\n        for (const p of this[PIPES]) {\n          p.dest.write(data as RType)\n        }\n        if (!this[DISCARDED]) super.emit('data', data)\n      }\n    }\n\n    for (const p of this[PIPES]) {\n      p.end()\n    }\n    const ret = super.emit('end')\n    this.removeAllListeners('end')\n    return ret\n  }\n\n  /**\n   * Return a Promise that resolves to an array of all emitted data once\n   * the stream ends.\n   */\n  async collect(): Promise {\n    const buf: RType[] & { dataLength: number } = Object.assign([], {\n      dataLength: 0,\n    })\n    if (!this[OBJECTMODE]) buf.dataLength = 0\n    // set the promise first, in case an error is raised\n    // by triggering the flow here.\n    const p = this.promise()\n    this.on('data', c => {\n      buf.push(c)\n      if (!this[OBJECTMODE])\n        buf.dataLength += (c as Minipass.BufferOrString).length\n    })\n    await p\n    return buf\n  }\n\n  /**\n   * Return a Promise that resolves to the concatenation of all emitted data\n   * once the stream ends.\n   *\n   * Not allowed on objectMode streams.\n   */\n  async concat(): Promise {\n    if (this[OBJECTMODE]) {\n      throw new Error('cannot concat in objectMode')\n    }\n    const buf = await this.collect()\n    return (\n      this[ENCODING]\n        ? buf.join('')\n        : Buffer.concat(buf as Buffer[], buf.dataLength)\n    ) as RType\n  }\n\n  /**\n   * Return a void Promise that resolves once the stream ends.\n   */\n  async promise(): Promise {\n    return new Promise((resolve, reject) => {\n      this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n      this.on('error', er => reject(er))\n      this.on('end', () => resolve())\n    })\n  }\n\n  /**\n   * Asynchronous `for await of` iteration.\n   *\n   * This will continue emitting all chunks until the stream terminates.\n   */\n  [Symbol.asyncIterator](): AsyncGenerator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = async (): Promise> => {\n      this.pause()\n      stopped = true\n      return { value: undefined, done: true }\n    }\n    const next = (): Promise> => {\n      if (stopped) return stop()\n      const res = this.read()\n      if (res !== null) return Promise.resolve({ done: false, value: res })\n\n      if (this[EOF]) return stop()\n\n      let resolve!: (res: IteratorResult) => void\n      let reject!: (er: unknown) => void\n      const onerr = (er: unknown) => {\n        this.off('data', ondata)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        reject(er)\n      }\n      const ondata = (value: RType) => {\n        this.off('error', onerr)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        this.pause()\n        resolve({ value, done: !!this[EOF] })\n      }\n      const onend = () => {\n        this.off('error', onerr)\n        this.off('data', ondata)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        resolve({ done: true, value: undefined })\n      }\n      const ondestroy = () => onerr(new Error('stream destroyed'))\n      return new Promise>((res, rej) => {\n        reject = rej\n        resolve = res\n        this.once(DESTROYED, ondestroy)\n        this.once('error', onerr)\n        this.once('end', onend)\n        this.once('data', ondata)\n      })\n    }\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.asyncIterator]() {\n        return this\n      },\n      [Symbol.asyncDispose]: async () => {},\n    }\n  }\n\n  /**\n   * Synchronous `for of` iteration.\n   *\n   * The iteration will terminate when the internal buffer runs out, even\n   * if the stream has not yet terminated.\n   */\n  [Symbol.iterator](): Generator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = (): IteratorReturnResult => {\n      this.pause()\n      this.off(ERROR, stop)\n      this.off(DESTROYED, stop)\n      this.off('end', stop)\n      stopped = true\n      return { done: true, value: undefined }\n    }\n\n    const next = (): IteratorResult => {\n      if (stopped) return stop()\n      const value = this.read()\n      return value === null ? stop() : { done: false, value }\n    }\n\n    this.once('end', stop)\n    this.once(ERROR, stop)\n    this.once(DESTROYED, stop)\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.iterator]() {\n        return this\n      },\n      [Symbol.dispose]: () => {},\n    }\n  }\n\n  /**\n   * Destroy a stream, preventing it from being used for any further purpose.\n   *\n   * If the stream has a `close()` method, then it will be called on\n   * destruction.\n   *\n   * After destruction, any attempt to write data, read data, or emit most\n   * events will be ignored.\n   *\n   * If an error argument is provided, then it will be emitted in an\n   * 'error' event.\n   */\n  destroy(er?: unknown) {\n    if (this[DESTROYED]) {\n      if (er) this.emit('error', er)\n      else this.emit(DESTROYED)\n      return this\n    }\n\n    this[DESTROYED] = true\n    this[DISCARDED] = true\n\n    // throw away all buffered data, it's never coming out\n    this[BUFFER].length = 0\n    this[BUFFERLENGTH] = 0\n\n    const wc = this as Minipass & {\n      close?: () => void\n    }\n    if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n    if (er) this.emit('error', er)\n    // if no error to emit, still reject pending promises\n    else this.emit(DESTROYED)\n\n    return this\n  }\n\n  /**\n   * Alias for {@link isStream}\n   *\n   * Former export location, maintained for backwards compatibility.\n   *\n   * @deprecated\n   */\n  static get isStream() {\n    return isStream\n  }\n}\n", "import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\, and //?/UNC/host/share/ or\n// //host/share into \\\\host\\share\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncLongRegexp = /^\\\\\\\\\\?\\\\UNC\\\\([^\\\\]+\\\\[^\\\\]+)\\\\?$/i\nconst uncShareRegexp = /^\\\\\\\\[^\\\\?]+\\\\[^\\\\]+$/\nconst uncToDrive = (rootPath: string): string =>\n  rootPath\n    .replace(/\\//g, '\\\\')\n    .replace(uncDriveRegexp, '$1\\\\')\n    .replace(uncLongRegexp, '\\\\\\\\$1\\\\')\n    .replace(uncShareRegexp, '$&\\\\')\n\n// path.win32.parse() only finds the //?/UNC/ of a long UNC root\nconst longUncRoot =\n  /^[\\\\/]{2}\\?[\\\\/]unc[\\\\/][^\\\\/]+[\\\\/][^\\\\/]+(?:[\\\\/]|$)/i\n\n// //?/c:/x is the same path as c:/x\nconst longDrivePrefix = /^[\\\\/]{2}\\?[\\\\/](?=[a-z]:)/i\n// //?/UNC/host/share/x is the same path as //host/share/x. This\n// matches up to the / after UNC, which with a \\ in front of it is\n// the // in front of the host.\nconst longUncPrefix = /^[\\\\/]{2}\\?[\\\\/]unc(?=[\\\\/][^\\\\/]+[\\\\/][^\\\\/])/i\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new LRUCache({ max: 2 ** 12 })\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new LRUCache({ max: 2 ** 12 })\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /* c8 ignore start */\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   *\n   * @deprecated\n   */\n  get path(): string {\n    return this.parentPath\n  }\n  /* c8 ignore stop */\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * The file system methods that this Path uses, for a new root on\n   * another drive or UNC share.\n   *\n   * @internal\n   */\n  get fs(): FSOption {\n    return this.#fs\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return longUncRoot.exec(path)?.[0] ?? win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    // a root with no drive or UNC host is the root of this path\n    if (rootPath === this.root.name || /^[\\\\/]$/.test(rootPath)) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(rootPath, {\n      nocase: this.nocase,\n      fs: this.fs,\n    }).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    return uncToDrive(rootPath.toUpperCase()) === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    // use the same root as resolve() does for these paths\n    if (typeof cwd === 'string' && !cwd.startsWith('file://')) {\n      cwd = cwd.replace(longDrivePrefix, '').replace(longUncPrefix, '\\\\')\n    }\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n", "// this is just a very light wrapper around 2 arrays with an offset index\n\nimport type { ParseReturnFiltered } from 'minimatch'\nimport { GLOBSTAR } from 'minimatch'\n\n/**\n * One portion of a parsed minimatch pattern: a string, a Matcher for\n * a portion with magic, or GLOBSTAR for `**`.\n */\nexport type MMPattern = ParseReturnFiltered\n\n/** The Matcher that minimatch makes for a portion with magic. */\nexport type MMMatcher = Exclude\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\nconst customInspect = Symbol.for('nodejs.util.inspect.custom')\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // //?/UNC/host/share/x => ['//?/UNC/host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share', or\n        // '' / '' / '?' / 'UNC' / 'host' / 'share'\n        const n = this.#isLongUNC() ? 6 : 4\n        const proot = this.#patternList.slice(0, n)\n        const groot = this.#globList.slice(0, n)\n        const prest = this.#patternList.slice(n)\n        const grest = this.#globList.slice(n)\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [...proot, ''].join('/')\n        const g = [...groot, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = `${p1 as string}/`\n        const g = `${g1}/`\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  [customInspect]() {\n    return `Pattern <${this.#globList.slice(this.#index).join('/')}>`\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a Matcher, for a portion with magic\n   */\n  isMatcher(): boolean {\n    return typeof this.#patternList[this.#index] === 'object'\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  // the root is //?/UNC/host/share, the same as //host/share\n  #isLongUNC(): boolean {\n    const pl = this.#patternList\n    return (\n      pl[2] === '?' && typeof pl[3] === 'string' && /^unc$/i.test(pl[3])\n    )\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    // the host and share, after //?/UNC/ in a long UNC path\n    const h = this.#isLongUNC() ? 4 : 2\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[h] === 'string' &&\n          !!pl[h] &&\n          typeof pl[h + 1] === 'string' &&\n          !!pl[h + 1])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n", "// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport type { MinimatchOptions } from 'minimatch'\nimport { escape, Minimatch } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport type { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n  /**\n   * The escaped glob for the directory that a pattern starting with\n   * `/` is rooted at, with no trailing `/`.\n   */\n  slashRoot: string\n\n  /**\n   * Patterns that start with `/` (but not drive letters or UNC paths\n   * on Windows) start at the `root` option if it is set, or else at\n   * the root of `cwd`, the same as non-ignored patterns. If `cwd` is\n   * not provided, they start at `/`.\n   */\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      normalize,\n      platform = defaultPlatform,\n      root,\n      windowsPathsNoEscape,\n      allowWindowsEscape,\n      braceExpandMax = 10_000,\n    }: GlobWalkerOpts,\n    cwd?: Path,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    windowsPathsNoEscape =\n      !!windowsPathsNoEscape || allowWindowsEscape === false\n    this.mmopts = {\n      braceExpandMax,\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      normalize,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n      windowsPathsNoEscape,\n    }\n    const slashRoot = cwd?.resolve(root ?? '/').fullpath() ?? '/'\n    this.slashRoot = escape(\n      slashRoot.replace(/\\\\/g, '/').replace(/\\/$/, ''),\n      { magicalBraces: true, windowsPathsNoEscape },\n    )\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const glob =\n        p.root() === '/' ?\n          `${this.slashRoot}/${p.rest()?.globString() ?? ''}`\n        : p.globString()\n      const m = new Minimatch(glob, this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = `${p.fullpath()}/`\n    const relative = `${p.relative() || '.'}/`\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n", "// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport type { MMMatcher, MMPattern, Pattern } from './pattern.js'\nimport type { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path, in\n * this walk step and the steps that led to it.\n *\n * A step only adds to it before it makes the caches for the next\n * steps, so a copy can look up the chain of caches before it, in\n * place of copying their entries. A pattern for a path that a cache\n * up the chain has already seen is added to that cache's set, so that\n * the other steps that share it see it too. Paths are keyed by their\n * full path, because path-scurry can make a new Path object for the\n * same path once its cache of children is full.\n */\nexport class HasWalkedCache {\n  parent?: HasWalkedCache\n  store?: Map>\n  constructor(parent?: HasWalkedCache) {\n    this.parent = parent\n  }\n  copy() {\n    return new HasWalkedCache(this)\n  }\n  // the set for the path in this cache, or the closest one before it\n  #find(fullpath: string): Set | undefined {\n    const set = this.store?.get(fullpath)\n    return set || !this.parent ? set : this.parent.#find(fullpath)\n  }\n\n  hasWalked(target: Path, pattern: Pattern) {\n    return !!this.#find(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.#find(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else\n      (this.store ??= new Map()).set(\n        fullpath,\n        new Set([pattern.globString()]),\n      )\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n * The store maps each path to {@link MatchRecord.ABSOLUTE} and\n * {@link MatchRecord.IF_DIR} flags.\n */\nexport class MatchRecord {\n  static readonly ABSOLUTE = 2\n  static readonly IF_DIR = 1\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n =\n      (absolute ? MatchRecord.ABSOLUTE : 0) |\n      (ifDir ? MatchRecord.IF_DIR : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (typeof p === 'object') {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (typeof p === 'object') {\n          results.testMatcher(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (typeof rp === 'object') {\n        this.testMatcher(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testMatcher(\n    e: Path,\n    p: MMMatcher,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    // an entry name is one path portion, with no `/`\n    if (!p.testUnchecked(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n", "/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport type { Form } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport type { IgnoreLike } from './ignore.js'\nimport { Ignore } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport type { Pattern } from './pattern.js'\nimport { MatchRecord, Processor } from './processor.js'\n\nconst { ABSOLUTE, IF_DIR } = MatchRecord\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  braceExpandMax?: number\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike | ReadonlyArray\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  normalize?: boolean | Form\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Path[]\n  : O extends GWOFileTypesFalse ? string[]\n  : O extends GWOFileTypesUnset ? string[]\n  : (Path | string)[]\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike | ReadonlyArray,\n  opts: GlobWalkerOpts,\n  cwd: Path,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts, cwd)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts, cwd)\n  : (ignore as IgnoreLike)\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => unknown)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts, path)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => unknown) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => unknown) {\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(\n    inPath: Path,\n    ifDir: boolean,\n  ): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    let e: Path\n    if (this.opts.realpath) {\n      rpc = inPath.realpathCached() || (await inPath.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    } else {\n      e = inPath\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(inPath: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    let e: Path\n    if (this.opts.realpath) {\n      rpc = inPath.realpathCached() || inPath.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    } else {\n      e = inPath\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    this.#matchEmitChecked(e, absolute)\n  }\n\n  // emit a match that is known to not be seen or ignored yet\n  #matchEmitChecked(e: Path, absolute: boolean) {\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith(`..${this.#sep}`) ?\n          `.${this.#sep}`\n        : ''\n      this.matchEmit(!rel ? `.${mark}` : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    // matchCheckSync just checked that it is not seen or ignored, and\n    // nothing can have changed since\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.#matchEmitChecked(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => unknown) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) return cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of processor.matches.store) {\n      if (this.#ignored(m)) continue\n      tasks++\n      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>\n        next(),\n      )\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processorx: Processor,\n    cb: () => unknown,\n  ) {\n    const proc = processorx.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of proc.matches.store) {\n      if (this.#ignored(m)) continue\n      tasks++\n      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>\n        next(),\n      )\n    }\n    for (const [target, patterns] of proc.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, proc.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => unknown) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) return cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of processor.matches.store) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    const proc = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of proc.matches.store) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))\n    }\n    for (const [target, patterns] of proc.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, proc.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  // each Path is only emitted once (see GlobUtil.seen), so the results\n  // do not need to be deduped\n  matches: Result[] = []\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.push(e)\n  }\n\n  async walk(): Promise[]> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Result[] {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      void target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n", "import type { Form, MinimatchOptions } from 'minimatch'\nimport { Minimatch } from 'minimatch'\nimport type { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport type { FSOption, Path } from 'path-scurry'\nimport {\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport type { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be either a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignored` and `childrenIgnored`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  readonly ignore?: string | string[] | IgnoreLike | ReadonlyArray\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Normalize unicode in the pattern, and in the file names that it is\n   * matched against, with this form: `'NFC'`, `'NFD'`, `'NFKC'`, or\n   * `'NFKD'`. `true` means `'NFC'`. This is passed to minimatch, so it\n   * applies to the portions of the pattern with magic, and to the\n   * `ignore` patterns.\n   *\n   * The portions of the pattern without magic are looked up with\n   * path-scurry, which already compares the names of the entries\n   * that it knows in their `'NFKD'` form.\n   */\n  normalize?: boolean | Form\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n\n  /**\n   * max number of `{...}` patterns to expand. Default `1_000`.\n   *\n   * Note: this is much less than minimatch's default of `100_000`,\n   * because Glob has higher memory requirements due to walking\n   * the file system tree.\n   */\n  braceExpandMax?: number\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike | ReadonlyArray\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[] | ReadonlyArray\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    let p: string[] = typeof pattern === 'string' ? [pattern] : pattern\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      p = p.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      p = p.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = p\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      braceExpandMax: 10_000,\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      // default nocase based on platform\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return await new GlobWalker(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).walk()\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return new GlobWalker(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).walkSync()\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n", "import { Minimatch } from 'minimatch'\nimport type { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  for (const p of Array.isArray(pattern) ? pattern : [pattern]) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n", "import { escape, unescape } from 'minimatch'\nimport type { Minipass } from 'minipass'\nimport type { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type { Form } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n"],
+  "mappings": "qNAAO,IAAMA,GAAW,CACtBC,EACAC,EACAC,IACE,CACF,IAAMC,EAAKH,aAAa,OAASI,GAAWJ,EAAGE,CAAG,EAAIF,EAChDK,EAAKJ,aAAa,OAASG,GAAWH,EAAGC,CAAG,EAAID,EAEhDK,EAAIH,IAAO,MAAQE,GAAM,SAAQE,GAAA,OAAMJ,EAAIE,EAAIH,CAAG,EAExD,OACEI,GAAK,CACH,MAAOA,EAAE,CAAC,EACV,IAAKA,EAAE,CAAC,EACR,IAAKJ,EAAI,MAAM,EAAGI,EAAE,CAAC,CAAC,EACtB,KAAMJ,EAAI,MAAMI,EAAE,CAAC,EAAIH,EAAG,OAAQG,EAAE,CAAC,CAAC,EACtC,KAAMJ,EAAI,MAAMI,EAAE,CAAC,EAAID,EAAG,MAAM,EAGtC,EAnBaE,GAAA,SAAQR,GAqBrB,IAAMK,GAAa,CAACI,EAAaN,IAAe,CAC9C,IAAMO,EAAIP,EAAI,MAAMM,CAAG,EACvB,OAAOC,EAAIA,EAAE,CAAC,EAAI,IACpB,EAEaC,GAAQ,CACnBV,EACAC,EACAC,IACgC,CAChC,IAAIS,EACFC,EACAC,EACAC,EACAC,EACEC,EAAKd,EAAI,QAAQF,CAAC,EAClBiB,EAAKf,EAAI,QAAQD,EAAGe,EAAK,C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A,KAAKM,EAASC,CAAO,EAAE,QAAO,CAC3C,CAGa,QAAA,WAAab,GACb,QAAA,OAAS,OAAO,OAAOC,GAAY,CAAE,KAAMD,EAAc,CAAE,EAC3D,QAAA,YAAcG,GACd,QAAA,QAAU,OAAO,OAAOC,GAAa,CAChD,KAAMD,GACP,EACY,QAAA,KAAO,OAAO,OAAOD,GAAU,CAC1C,OAAQF,GACR,QAASG,GACV,EAEY,QAAA,KAAO,OAAO,OAAOW,GAAO,CACvC,KAAMA,GACN,SAAAZ,GACA,KAAA,QAAA,KACA,WAAAD,GACA,OAAA,QAAA,OACA,eAAAD,GACA,WAAA,QAAA,WACA,YAAAI,GACA,QAAA,QAAA,QACA,gBAAAD,GACA,YAAA,QAAA,YACA,KAAAG,GAAA,KACA,SAAAC,GAAA,SACA,OAAAF,GAAA,OACA,SAAAA,GAAA,SACD,EACD,QAAA,KAAK,KAAO,QAAA",
+  "names": ["balanced", "a", "b", "str", "ma", "maybeMatch", "mb", "r", "exports", "reg", "m", "range", "begs", "beg", "left", "right", "result", "ai", "bi", "i", "exports", "expand", "balanced_match_1", "escSlash", "escOpen", "escClose", "escComma", "escPeriod", "escSlashPattern", "escOpenPattern", "escClosePattern", "escCommaPattern", "escPeriodPattern", "slashPattern", "openPattern", "closePattern", "commaPattern", "periodPattern", "numeric", "str", "escapeBraces", "unescapeBraces", "pushAll", "target", "items", "i", "parseCommaParts", "parts", "carry", "m", "tail", "pre", "body", "post", "p", "options", "max", "maxLength", "maxDepth", "maxRewrites", "expand_", "embrace", "isPadded", "el", "lte", "y", "gte", "combine", "acc", "values", "dropEmpties", "out", "length", "v", "expansion", "expandSequence", "isAlphaSequence", "n", "N", "x", "width", "incr", "test", "pad", "c", "need", "z", "depth", "isTop", "rewrites", "firstGroup", "isNumericSequence", "isSequence", "isOptions", "dropsEmpties", "d", "valuesLength", "outer", "j", "expanded", "k", "digit", "a", "b", "prefix", "d", "alts", "s", "fixed", "lo", "hi", "ra", "rb", "zeros", "nines", "out", "last", "nonneg", "width", "len", "numericRange", "loStr", "hiStr", "neg", "exports", "posixClasses", "braceEscape", "s", "noMatch", "parseClass", "glob", "position", "nocase", "form", "norm", "c", "n", "pos", "ranges", "negs", "i", "sawStart", "escaping", "negate", "endPos", "rangeStart", "WHILE", "cls", "unip", "neg", "sranges", "snegs", "comb", "exports", "numeric_range_js_1", "parse_class_js_1", "MATCH", "extTypes", "lit", "ch", "reEscape", "s", "newFoldRe", "foldCache", "foldRe", "re", "litMatch", "l", "c", "code", "ascii", "tokenize", "p", "nocase", "noext", "form", "mark", "toks", "i", "m", "start", "end", "r", "alts", "e", "consumed", "pair", "pairs", "stack", "tok", "build", "top", "seq", "close", "sub", "normalize", "items", "out", "run", "flush", "it", "a", "compile", "id", "split", "next", "item", "after", "entry", "show", "lines", "seen", "ref", "walk", "indent", "line", "desc", "o", "State", "gen", "sameState", "b", "marks", "size", "Sim", "#marks", "dots", "dotStart", "state", "n", "#visit", "node", "#addThread", "has", "th", "stateKey", "ids", "runs", "DFA_BUDGET", "Dfa", "#start", "#states", "#size", "#plain", "#dotStart", "#sim", "#dotSim", "#make", "#intern", "key", "found", "#clear", "d", "linear", "nodes", "testLinear", "chars", "ni", "ci", "starNi", "starCi", "lengths", "min", "max", "lo", "hi", "itemLengths", "loop", "hasAffix", "lits", "j", "slashOrSurrogate", "surrogate", "codePoints", "noSlash", "Matcher", "#dotsSim", "#literal", "#literalFold", "#literalRe", "#linear", "#wild", "#min", "#max", "#prefix", "#suffix", "#prefixStr", "#suffixStr", "#affix", "#dfa", "#form", "pattern", "options", "literal", "#test", "most", "least", "prefix", "sim", "dfa", "str", "exports", "MAX_PATTERN_LENGTH", "assertValidPattern", "pattern", "exports", "escape", "s", "windowsPathsNoEscape", "magicalBraces", "exports", "unescape", "s", "windowsPathsNoEscape", "magicalBraces", "exports", "brace_expansion_1", "nonrecursive_glob_match_1", "assert_valid_pattern_js_1", "escape_js_1", "unescape_js_1", "minimatch", "p", "pattern", "options", "cachedMinimatch", "exports", "cache", "cacheMax", "key", "mm", "Minimatch", "defaultPlatform", "path", "filter", "ext", "a", "b", "defaults", "def", "orig", "list", "braceExpand", "RANGE_MIN", "rangeRe", "match", "f", "globMagic", "classEnd", "start", "i", "sawStart", "c", "literal", "noext", "lit", "close", "body", "extSafe", "depth", "lastSplit", "lastChecked", "portionMatch", "endIndex", "last", "lastStart", "prev", "prevStart", "isDots", "isDrive", "isLongUNC", "uncHost", "h", "host", "share", "walkable", "dot", "dotPortion", "end", "sep", "k", "n", "isSep", "s", "nextSep", "from", "lastSep", "PENDING", "#endCheck", "#literalCheck", "#level2", "#form", "#literals", "#shapes", "#endRows", "#matchers", "#pending", "#rangeMark", "#globstarParts", "awe", "drives", "row", "#rootIndex", "r", "lits", "l", "p0", "p1", "p2", "#norm", "part", "#expandBraces", "rawGlobParts", "#slashSplit", "set", "_", "__", "isUNC", "ss", "merged", "len", "groups", "parts", "g", "drop", "first", "rest", "glob", "globParts", "partset", "j", "optimizationLevel", "gs", "root", "#canMatch", "ends", "ROWS", "resolves", "tailStart", "shape", "m", "#walk", "#matchShape", "file", "x", "t", "head", "e", "next", "#cachedSplit", "#split", "isWindows", "preserveMultipleSlashes", "normalize", "#levelTwoFileOptimize", "didSomething", "dd", "braceExpandMax", "splitCells", "maxSplitCells", "gss", "addedCells", "other", "splin", "keys", "rows", "stars", "ok", "changed", "negate", "negateOffset", "#matchRow", "resolved", "partial", "fileStartIndex", "patternStartIndex", "fh", "ph", "fileDrive", "fileUNC", "patternDrive", "patternUNC", "fdi", "pdi", "fd", "pd", "#matchGlobstar", "#matchOne", "fileIndex", "patternIndex", "tail", "segments", "#getGlobstarParts", "headEnd", "fileTailMatch", "sawSome", "#matchGlobStarBodySections", "byStart", "found", "firstgs", "lastgs", "current", "nonGsParts", "nonGsPartsSums", "bodySegments", "fileLength", "bodyIndex", "globStarDepth", "sawTail", "tried", "bs", "need", "after", "sub", "fileEnd", "fi", "pi", "pl", "fl", "code", "mark", "marked", "lo", "hi", "portion", "nocase", "nocaseMagicOnly", "rangeMark", "split", "can", "ff", "filename", "escape_js_2", "unescape_js_2", "node_diagnostics_channel_1", "exports", "P", "j", "R", "diagnostics_channel_js_1", "I", "perf_js_1", "hasSubscribers", "warned", "PROCESS", "emitWarning", "msg", "type", "code", "fn", "shouldWarn", "isPosInt", "n", "getUintArray", "max", "ZeroArray", "size", "Stack", "_Stack", "#constructing", "HeapCls", "s", "LRUCache", "_LRUCache", "#max", "#maxSize", "#dispose", "#onInsert", "#disposeAfter", "#fetchMethod", "#memoMethod", "#perf", "#size", "#calculatedSize", "#keyMap", "#keyList", "#valList", "#next", "#prev", "#head", "#tail", "#free", "#disposed", "#sizes", "#starts", "#ttls", "#autopurgeTimers", "#hasDispose", "#hasFetchMethod", "#hasDisposeAfter", "#hasOnInsert", "c", "p", "#isBackgroundFetch", "k", "index", "options", "context", "#backgroundFetch", "#moveToTail", "#indexes", "#rindexes", "#isStale", "ttl", "ttlResolution", "ttlAutopurge", "updateAgeOnGet", "updateAgeOnHas", "allowStale", "dispose", "onInsert", "disposeAfter", "noDisposeOnSet", "noUpdateTTL", "maxSize", "maxEntrySize", "sizeCalculation", "fetchMethod", "memoMethod", "noDeleteOnFetchRejection", "noDeleteOnStaleGet", "allowStaleOnFetchRejection", "allowStaleOnFetchAbort", "ignoreFetchAbort", "backgroundFetchSize", "perf", "UintArray", "#initializeSizeTracking", "#initializeTTLTracking", "key", "ttls", "starts", "purgeTimers", "#setItemTTL", "start", "setPurgeTimer", "#updateItemAge", "t", "#delete", "getRemainingTTL", "#statusTTL", "status", "cachedNow", "getNow", "age", "sizes", "#removeItemSize", "#requireSize", "v", "#addItemSize", "#evict", "_i", "_s", "_st", "_k", "_v", "i", "#isValidIndex", "getOptions", "value", "#get", "thisp", "deleted", "entry", "remain", "arr", "#set", "setOptions", "result", "bf", "isBF", "oldVal", "oldValue", "setType", "dt", "task", "val", "free", "head", "hasOptions", "#has", "peekOptions", "#peek", "ac", "signal", "fetchOpts", "cb", "updateCache", "aborted", "ignoreAbort", "proceed", "fetchFail", "vl", "eb", "er", "allowStaleAborted", "noDelete", "pcall", "res", "rej", "fmp", "b", "fetchOptions", "ths", "#fetch", "forceRefresh", "stale", "isStale", "staleVal", "#forceFetch", "memoOptions", "#memo", "refresh", "vv", "fetching", "#connect", "reason", "#clear", "pi", "ni", "proc", "node_events_1", "node_stream_1", "__importDefault", "node_string_decoder_1", "isStream", "s", "Minipass", "exports", "isReadable", "isWritable", "EOF", "MAYBE_EMIT_END", "EMITTED_END", "EMITTING_END", "EMITTED_ERROR", "CLOSED", "READ", "FLUSH", "FLUSHCHUNK", "ENCODING", "DECODER", "FLOWING", "PAUSED", "RESUME", "BUFFER", "PIPES", "BUFFERLENGTH", "BUFFERPUSH", "BUFFERSHIFT", "OBJECTMODE", "DESTROYED", "ERROR", "EMITDATA", "EMITEND", "EMITEND2", "ASYNC", "ABORT", "ABORTED", "SIGNAL", "DATALISTENERS", "DISCARDED", "defer", "fn", "nodefer", "isEndish", "ev", "isArrayBufferLike", "b", "isArrayBufferView", "Pipe", "src", "dest", "opts", "_er", "PipeProxyErrors", "er", "isObjectModeOptions", "o", "isEncodingOptions", "args", "options", "signal", "_enc", "_om", "a", "_", "chunk", "encoding", "cb", "n", "ret", "c", "noDrain", "ended", "p", "handler", "h", "data", "buf", "resolve", "reject", "stopped", "stop", "res", "onerr", "ondata", "onend", "ondestroy", "value", "rej", "next", "wc", "lru_cache_1", "node_path_1", "node_url_1", "fs_1", "actualFS", "__importStar", "realpathSync", "promises_1", "minipass_1", "defaultFS", "fsFromOption", "fsOption", "uncDriveRegexp", "uncLongRegexp", "uncShareRegexp", "uncToDrive", "rootPath", "longUncRoot", "longDrivePrefix", "longUncPrefix", "eitherSep", "UNKNOWN", "IFIFO", "IFCHR", "IFDIR", "IFBLK", "IFREG", "IFLNK", "IFSOCK", "IFMT", "IFMT_UNKNOWN", "READDIR_CALLED", "LSTAT_CALLED", "ENOTDIR", "ENOENT", "ENOREADLINK", "ENOREALPATH", "ENOCHILD", "TYPEMASK", "entToType", "s", "normalizeCache", "normalize", "c", "n", "normalizeNocaseCache", "normalizeNocase", "ResolveCache", "exports", "ChildrenCache", "maxSize", "a", "setAsCwd", "PathBase", "#fs", "#dev", "#mode", "#nlink", "#uid", "#gid", "#rdev", "#blksize", "#ino", "#size", "#blocks", "#atimeMs", "#mtimeMs", "#ctimeMs", "#birthtimeMs", "#atime", "#mtime", "#ctime", "#birthtime", "#matchName", "#depth", "#fullpath", "#fullpathPosix", "#relative", "#relativePosix", "#type", "#children", "#linkTarget", "#realpath", "name", "type", "root", "roots", "nocase", "children", "opts", "path", "dirParts", "#resolveParts", "p", "part", "cached", "pathPart", "fullpath", "pchild", "pv", "fp", "pfpp", "fpp", "ifmt", "target", "read", "linkTarget", "er", "#readlinkFail", "#readdirSuccess", "#markENOENT", "#markChildrenENOENT", "#markENOREALPATH", "#markENOTDIR", "#readdirFail", "code", "#lstatFail", "ter", "#readdirAddChild", "e", "#readdirMaybePromoteChild", "#readdirAddNewChild", "child", "#readdirPromoteChild", "index", "v", "#applyStat", "st", "atime", "atimeMs", "birthtime", "birthtimeMs", "blksize", "blocks", "ctime", "ctimeMs", "dev", "gid", "ino", "mode", "mtime", "mtimeMs", "nlink", "rdev", "size", "uid", "#onReaddirCB", "#readdirCBInFlight", "#callOnReaddirCB", "cbs", "cb", "allowZalgo", "entries", "#asyncReaddirInFlight", "resolve", "res", "dirs", "walkFilter", "rp", "oldCwd", "changed", "PathWin32", "_PathWin32", "compare", "PathScurryWin32", "PathPosix", "_PathPosix", "_rootPath", "PathScurryBase", "#resolveCache", "#resolvePosixCache", "cwd", "pathImpl", "sep", "childrenCacheSize", "fs", "cwdPath", "split", "prev", "len", "joinSep", "abs", "sawFirst", "l", "paths", "r", "i", "result", "entry", "withFileTypes", "follow", "filter", "results", "walk", "dir", "next", "start", "rej", "options", "queue", "processing", "process", "paused", "onReaddir", "didRealpaths", "promises", "sync", "PathScurryPosix", "_dir", "PathScurryDarwin", "minimatch_1", "isPatternList", "pl", "isGlobList", "gl", "customInspect", "Pattern", "_Pattern", "#patternList", "#globList", "#index", "#platform", "#rest", "#globString", "#isDrive", "#isUNC", "#isAbsolute", "#followGlobstar", "patternList", "globList", "index", "platform", "#isLongUNC", "proot", "groot", "prest", "grest", "p", "g", "p1", "g1", "h", "exports", "minimatch_1", "pattern_js_1", "defaultPlatform", "Ignore", "ignored", "nobrace", "nocase", "noext", "noglobstar", "normalize", "platform", "root", "windowsPathsNoEscape", "allowWindowsEscape", "braceExpandMax", "cwd", "slashRoot", "ign", "mm", "i", "parsed", "globParts", "p", "glob", "m", "children", "absolute", "fullpath", "fullpaths", "relative", "relatives", "exports", "minimatch_1", "HasWalkedCache", "_HasWalkedCache", "parent", "#find", "fullpath", "set", "target", "pattern", "cached", "exports", "MatchRecord", "_MatchRecord", "absolute", "ifDir", "n", "current", "SubWalks", "subs", "p", "k", "Processor", "_Processor", "opts", "hasWalkedCache", "patterns", "processingSet", "t", "root", "rest", "changed", "rp", "rrest", "tp", "entries", "results", "e", "ep", "minipass_1", "ignore_js_1", "processor_js_1", "ABSOLUTE", "IF_DIR", "makeIgnore", "ignore", "opts", "cwd", "GlobUtil", "#onResume", "#ignore", "#sep", "patterns", "path", "m", "#ignored", "#childrenIgnored", "fn", "inPath", "ifDir", "rpc", "e", "s", "target", "absolute", "#matchEmitChecked", "ign", "abs", "mark", "rel", "pre", "p", "cb", "processor", "tasks", "next", "n", "t", "childrenCached", "_", "entries", "processorx", "proc", "children", "exports", "GlobWalker", "res", "rej", "GlobStream", "minimatch_1", "node_url_1", "path_scurry_1", "pattern_js_1", "walker_js_1", "defaultPlatform", "Glob", "pattern", "opts", "p", "Scurry", "nocaseMagicOnly", "mmo", "mms", "matchSet", "globParts", "set", "m", "i", "g", "exports", "minimatch_1", "hasMagic", "pattern", "options", "p", "exports", "globStreamSync", "globStream", "globSync", "globIterateSync", "globIterate", "minimatch_1", "glob_js_1", "has_magic_js_1", "minimatch_2", "glob_js_2", "has_magic_js_2", "ignore_js_1", "pattern", "options", "glob_"]
 }
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.d.ts b/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.d.ts
index 4e4ed3cdf75d606cc9e43bf293cbf7347da3df99..382c842d76602a609cf2bb9efa9f12b877817950 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.d.ts
@@ -1,5 +1,12 @@
+import type { ParseReturnFiltered } from 'minimatch';
 import { GLOBSTAR } from 'minimatch';
-export type MMPattern = string | RegExp | typeof GLOBSTAR;
+/**
+ * One portion of a parsed minimatch pattern: a string, a Matcher for
+ * a portion with magic, or GLOBSTAR for `**`.
+ */
+export type MMPattern = ParseReturnFiltered;
+/** The Matcher that minimatch makes for a portion with magic. */
+export type MMMatcher = Exclude;
 export type PatternList = [p: MMPattern, ...rest: MMPattern[]];
 export type UNCPatternList = [
     p0: '',
@@ -34,9 +41,9 @@ export declare class Pattern {
      */
     isGlobstar(): boolean;
     /**
-     * true if pattern() returns a regexp
+     * true if pattern() returns a Matcher, for a portion with magic
      */
-    isRegExp(): boolean;
+    isMatcher(): boolean;
     /**
      * The /-joined set of glob parts that make up this pattern
      */
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.d.ts.map
index 2432516afac5e23327340b377c7170f06b179f84..82cecff8f2ff882d4cb849f56875a4f32484709e 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,MAAM,MAAM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AE,MAAM,CAAA;gBAUrB,WAAW,EAAE,SAAS,EAAE,EACxB,QAAQ,EAAE,MAAM,EAAE,EAClB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,CAAC,QAAQ;IAkE3B,CAAC,aAAa,CAAC;IAIf;;OAEG;IACH,OAAO,IAAI,SAAS;IAIpB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAGnB;;OAEG;IACH,UAAU,IAAI,OAAO;IAGrB;;OAEG;IACH,SAAS,IAAI,OAAO;IAIpB;;OAEG;IACH,UAAU,IAAI,MAAM;IAUpB;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACH,IAAI,IAAI,OAAO,GAAG,IAAI;IAuBtB;;OAEG;IACH,KAAK,IAAI,OAAO;IAsBhB;;OAEG;IACH,OAAO,IAAI,OAAO;IAelB;;OAEG;IACH,UAAU,IAAI,OAAO;IAUrB;;OAEG;IACH,IAAI,IAAI,MAAM;IASd;;;OAGG;IACH,mBAAmB,IAAI,OAAO;IAQ9B;;OAEG;IACH,kBAAkB,IAAI,OAAO;CAM9B"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.js b/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.js
index 95f9075c5bfcb5707315428fb5b3accaeb2ff815..3e71d28fee5fd73c8d4cce4b92be744ed2b3b2df 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.js
@@ -48,19 +48,24 @@ class Pattern {
             // //host/share => ['//host/share/']
             // //host/share/ => ['//host/share/']
             // //host/share/x => ['//host/share/', 'x']
+            // //?/UNC/host/share/x => ['//?/UNC/host/share/', 'x']
             // /etc => ['/', 'etc']
             // / => ['/']
             if (this.isUNC()) {
-                // '' / '' / 'host' / 'share'
-                const [p0, p1, p2, p3, ...prest] = this.#patternList;
-                const [g0, g1, g2, g3, ...grest] = this.#globList;
+                // '' / '' / 'host' / 'share', or
+                // '' / '' / '?' / 'UNC' / 'host' / 'share'
+                const n = this.#isLongUNC() ? 6 : 4;
+                const proot = this.#patternList.slice(0, n);
+                const groot = this.#globList.slice(0, n);
+                const prest = this.#patternList.slice(n);
+                const grest = this.#globList.slice(n);
                 if (prest[0] === '') {
                     // ends in /
                     prest.shift();
                     grest.shift();
                 }
-                const p = [p0, p1, p2, p3, ''].join('/');
-                const g = [g0, g1, g2, g3, ''].join('/');
+                const p = [...proot, ''].join('/');
+                const g = [...groot, ''].join('/');
                 this.#patternList = [p, ...prest];
                 this.#globList = [g, ...grest];
                 this.length = this.#patternList.length;
@@ -73,8 +78,8 @@ class Pattern {
                     prest.shift();
                     grest.shift();
                 }
-                const p = p1 + '/';
-                const g = g1 + '/';
+                const p = `${p1}/`;
+                const g = `${g1}/`;
                 this.#patternList = [p, ...prest];
                 this.#globList = [g, ...grest];
                 this.length = this.#patternList.length;
@@ -82,7 +87,7 @@ class Pattern {
         }
     }
     [customInspect]() {
-        return 'Pattern <' + this.#globList.slice(this.#index).join('/') + '>';
+        return `Pattern <${this.#globList.slice(this.#index).join('/')}>`;
     }
     /**
      * The first entry in the parsed list of patterns
@@ -103,10 +108,10 @@ class Pattern {
         return this.#patternList[this.#index] === minimatch_1.GLOBSTAR;
     }
     /**
-     * true if pattern() returns a regexp
+     * true if pattern() returns a Matcher, for a portion with magic
      */
-    isRegExp() {
-        return this.#patternList[this.#index] instanceof RegExp;
+    isMatcher() {
+        return typeof this.#patternList[this.#index] === 'object';
     }
     /**
      * The /-joined set of glob parts that make up this pattern
@@ -140,11 +145,18 @@ class Pattern {
         this.#rest.#isDrive = this.#isDrive;
         return this.#rest;
     }
+    // the root is //?/UNC/host/share, the same as //host/share
+    #isLongUNC() {
+        const pl = this.#patternList;
+        return (pl[2] === '?' && typeof pl[3] === 'string' && /^unc$/i.test(pl[3]));
+    }
     /**
      * true if the pattern represents a //unc/path/ on windows
      */
     isUNC() {
         const pl = this.#patternList;
+        // the host and share, after //?/UNC/ in a long UNC path
+        const h = this.#isLongUNC() ? 4 : 2;
         return this.#isUNC !== undefined ?
             this.#isUNC
             : (this.#isUNC =
@@ -152,10 +164,10 @@ class Pattern {
                     this.#index === 0 &&
                     pl[0] === '' &&
                     pl[1] === '' &&
-                    typeof pl[2] === 'string' &&
-                    !!pl[2] &&
-                    typeof pl[3] === 'string' &&
-                    !!pl[3]);
+                    typeof pl[h] === 'string' &&
+                    !!pl[h] &&
+                    typeof pl[h + 1] === 'string' &&
+                    !!pl[h + 1]);
     }
     // pattern like C:/...
     // split = ['C:', ...]
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.js.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.js.map
index 2c3a0f403e0ddf8bd2cf748195c0edba08b72a70..7983d764f3bf09ccd8856b3eb19e3471866cc38d 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/pattern.js.map
@@ -1 +1 @@
-{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":";AAAA,yEAAyE;;;AAEzE,yCAAoC;AAgBpC,MAAM,aAAa,GAAG,CAAC,EAAe,EAAqB,EAAE,CAC3D,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAChB,MAAM,UAAU,GAAG,CAAC,EAAY,EAAkB,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAEnE,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAA;AAE9D;;;GAGG;AACH,MAAa,OAAO;IACT,YAAY,CAAa;IACzB,SAAS,CAAU;IACnB,MAAM,CAAQ;IACd,MAAM,CAAQ;IACd,SAAS,CAAiB;IACnC,KAAK,CAAiB;IACtB,WAAW,CAAS;IACpB,QAAQ,CAAU;IAClB,MAAM,CAAU;IAChB,WAAW,CAAU;IACrB,eAAe,GAAY,I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,EAAE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,CAChE,CAAC,CAAC;YACD,CAAC;YACH,CAAC,CAAC,EAAE,CAAA;IACR,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,CAAC,CACN,IAAI,CAAC,MAAM,KAAK,CAAC;YACjB,CAAC,IAAI,CAAC,UAAU,EAAE;YAClB,CAAC,IAAI,CAAC,eAAe,CACtB,CAAA;IACH,CAAC;IAED;;OAEG;IACH,kBAAkB;QAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;YAClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAzOD,0BAyOC","sourcesContent":["// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\nconst customInspect = Symbol.for('nodejs.util.inspect.custom')\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  [customInspect]() {\n    return 'Pattern <' + this.#globList.slice(this.#index).join('/') + '>'\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":";AAAA,yEAAyE;;;AAGzE,yCAAoC;AAwBpC,MAAM,aAAa,GAAG,CAAC,EAAe,EAAqB,EAAE,CAC3D,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAChB,MAAM,UAAU,GAAG,CAAC,EAAY,EAAkB,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAEnE,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAA;AA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ClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAxPD,0BAwPC","sourcesContent":["// this is just a very light wrapper around 2 arrays with an offset index\n\nimport type { ParseReturnFiltered } from 'minimatch'\nimport { GLOBSTAR } from 'minimatch'\n\n/**\n * One portion of a parsed minimatch pattern: a string, a Matcher for\n * a portion with magic, or GLOBSTAR for `**`.\n */\nexport type MMPattern = ParseReturnFiltered\n\n/** The Matcher that minimatch makes for a portion with magic. */\nexport type MMMatcher = Exclude\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\nconst customInspect = Symbol.for('nodejs.util.inspect.custom')\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // //?/UNC/host/share/x => ['//?/UNC/host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share', or\n        // '' / '' / '?' / 'UNC' / 'host' / 'share'\n        const n = this.#isLongUNC() ? 6 : 4\n        const proot = this.#patternList.slice(0, n)\n        const groot = this.#globList.slice(0, n)\n        const prest = this.#patternList.slice(n)\n        const grest = this.#globList.slice(n)\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [...proot, ''].join('/')\n        const g = [...groot, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = `${p1 as string}/`\n        const g = `${g1}/`\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  [customInspect]() {\n    return `Pattern <${this.#globList.slice(this.#index).join('/')}>`\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a Matcher, for a portion with magic\n   */\n  isMatcher(): boolean {\n    return typeof this.#patternList[this.#index] === 'object'\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  // the root is //?/UNC/host/share, the same as //host/share\n  #isLongUNC(): boolean {\n    const pl = this.#patternList\n    return (\n      pl[2] === '?' && typeof pl[3] === 'string' && /^unc$/i.test(pl[3])\n    )\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    // the host and share, after //?/UNC/ in a long UNC path\n    const h = this.#isLongUNC() ? 4 : 2\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[h] === 'string' &&\n          !!pl[h] &&\n          typeof pl[h + 1] === 'string' &&\n          !!pl[h + 1])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.d.ts b/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.d.ts
index ccedfbf2820f7d51167574666a80785ca1b91b07..99f8e14fd17cf261ed2155f464d7e5711f089108 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.d.ts
@@ -1,26 +1,39 @@
-import { MMRegExp } from 'minimatch';
-import { Path } from 'path-scurry';
-import { Pattern } from './pattern.js';
-import { GlobWalkerOpts } from './walker.js';
+import type { Path } from 'path-scurry';
+import type { MMMatcher, Pattern } from './pattern.js';
+import type { GlobWalkerOpts } from './walker.js';
 /**
- * A cache of which patterns have been processed for a given Path
+ * A cache of which patterns have been processed for a given Path, in
+ * this walk step and the steps that led to it.
+ *
+ * A step only adds to it before it makes the caches for the next
+ * steps, so a copy can look up the chain of caches before it, in
+ * place of copying their entries. A pattern for a path that a cache
+ * up the chain has already seen is added to that cache's set, so that
+ * the other steps that share it see it too. Paths are keyed by their
+ * full path, because path-scurry can make a new Path object for the
+ * same path once its cache of children is full.
  */
 export declare class HasWalkedCache {
-    store: Map>;
-    constructor(store?: Map>);
+    #private;
+    parent?: HasWalkedCache;
+    store?: Map>;
+    constructor(parent?: HasWalkedCache);
     copy(): HasWalkedCache;
-    hasWalked(target: Path, pattern: Pattern): boolean | undefined;
+    hasWalked(target: Path, pattern: Pattern): boolean;
     storeWalked(target: Path, pattern: Pattern): void;
 }
 /**
  * A record of which paths have been matched in a given walk step,
  * and whether they only are considered a match if they are a directory,
  * and whether their absolute or relative path should be returned.
+ * The store maps each path to {@link MatchRecord.ABSOLUTE} and
+ * {@link MatchRecord.IF_DIR} flags.
  */
 export declare class MatchRecord {
+    static readonly ABSOLUTE = 2;
+    static readonly IF_DIR = 1;
     store: Map;
     add(target: Path, absolute: boolean, ifDir: boolean): void;
-    entries(): [Path, boolean, boolean][];
 }
 /**
  * A collection of patterns that must be processed in a subsequent step
@@ -53,7 +66,7 @@ export declare class Processor {
     child(): Processor;
     filterEntries(parent: Path, entries: Path[]): Processor;
     testGlobstar(e: Path, pattern: Pattern, rest: Pattern | null, absolute: boolean): void;
-    testRegExp(e: Path, p: MMRegExp, rest: Pattern | null, absolute: boolean): void;
+    testMatcher(e: Path, p: MMMatcher, rest: Pattern | null, absolute: boolean): void;
     testString(e: Path, p: string, rest: Pattern | null, absolute: boolean): void;
 }
 //# sourceMappingURL=processor.d.ts.map
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.d.ts.map
index aa266fee4a0544a0a8f7fddceb347d7d059643e0..82e512cc8eae57ff198c049c12289bf57fb3ba88 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAa,OAAO,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C;;GAEG;AACH,qBAAa,cAAc;IACzB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;gBACnB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAa;IAGvD,IAAI;IAGJ,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAGxC,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;CAM3C;AAED;;;;GAIG;AACH,qBAAa,WAAW;IACtB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAY;IACpC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;IAMnD,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;CAOtC;AAED;;;GAGG;AACH,qBAAa,QAAQ;IACnB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,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AA;IACZ,IAAI,EAAE,cAAc,CAAA;gBAER,IAAI,EAAE,cAAc,EAAE,cAAc,CAAC,EAAE,cAAc;IAQjE,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE;IAmGjD,cAAc,IAAI,IAAI,EAAE;IAIxB,KAAK;IAQL,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS;IAqBvD,YAAY,CACV,CAAC,EAAE,IAAI,EACP,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IA8CnB,WAAW,CACT,CAAC,EAAE,IAAI,EACP,CAAC,EAAE,SAAS,EACZ,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IAWnB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,EAAE,QAAQ,EAAE,OAAO;CASvE"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.js b/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.js
index ee3bb4397e0b2d3aaff9b1e2053ac13a2af9f31b..9fea4a07b9b8f306d5094e02d7d45da484b0f845 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.js
@@ -4,26 +4,41 @@ Object.defineProperty(exports, "__esModule", { value: true });
 exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0;
 const minimatch_1 = require("minimatch");
 /**
- * A cache of which patterns have been processed for a given Path
+ * A cache of which patterns have been processed for a given Path, in
+ * this walk step and the steps that led to it.
+ *
+ * A step only adds to it before it makes the caches for the next
+ * steps, so a copy can look up the chain of caches before it, in
+ * place of copying their entries. A pattern for a path that a cache
+ * up the chain has already seen is added to that cache's set, so that
+ * the other steps that share it see it too. Paths are keyed by their
+ * full path, because path-scurry can make a new Path object for the
+ * same path once its cache of children is full.
  */
 class HasWalkedCache {
+    parent;
     store;
-    constructor(store = new Map()) {
-        this.store = store;
+    constructor(parent) {
+        this.parent = parent;
     }
     copy() {
-        return new HasWalkedCache(new Map(this.store));
+        return new HasWalkedCache(this);
+    }
+    // the set for the path in this cache, or the closest one before it
+    #find(fullpath) {
+        const set = this.store?.get(fullpath);
+        return set || !this.parent ? set : this.parent.#find(fullpath);
     }
     hasWalked(target, pattern) {
-        return this.store.get(target.fullpath())?.has(pattern.globString());
+        return !!this.#find(target.fullpath())?.has(pattern.globString());
     }
     storeWalked(target, pattern) {
         const fullpath = target.fullpath();
-        const cached = this.store.get(fullpath);
+        const cached = this.#find(fullpath);
         if (cached)
             cached.add(pattern.globString());
         else
-            this.store.set(fullpath, new Set([pattern.globString()]));
+            (this.store ??= new Map()).set(fullpath, new Set([pattern.globString()]));
     }
 }
 exports.HasWalkedCache = HasWalkedCache;
@@ -31,22 +46,19 @@ exports.HasWalkedCache = HasWalkedCache;
  * A record of which paths have been matched in a given walk step,
  * and whether they only are considered a match if they are a directory,
  * and whether their absolute or relative path should be returned.
+ * The store maps each path to {@link MatchRecord.ABSOLUTE} and
+ * {@link MatchRecord.IF_DIR} flags.
  */
 class MatchRecord {
+    static ABSOLUTE = 2;
+    static IF_DIR = 1;
     store = new Map();
     add(target, absolute, ifDir) {
-        const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
+        const n = (absolute ? MatchRecord.ABSOLUTE : 0) |
+            (ifDir ? MatchRecord.IF_DIR : 0);
         const current = this.store.get(target);
         this.store.set(target, current === undefined ? n : n & current);
     }
-    // match, absolute, ifdir
-    entries() {
-        return [...this.store.entries()].map(([path, n]) => [
-            path,
-            !!(n & 2),
-            !!(n & 1),
-        ]);
-    }
 }
 exports.MatchRecord = MatchRecord;
 /**
@@ -191,7 +203,7 @@ class Processor {
                     }
                 }
             }
-            else if (p instanceof RegExp) {
+            else if (typeof p === 'object') {
                 this.subwalks.add(t, pattern);
             }
         }
@@ -219,8 +231,8 @@ class Processor {
                 if (p === minimatch_1.GLOBSTAR) {
                     results.testGlobstar(e, pattern, rest, absolute);
                 }
-                else if (p instanceof RegExp) {
-                    results.testRegExp(e, p, rest, absolute);
+                else if (typeof p === 'object') {
+                    results.testMatcher(e, p, rest, absolute);
                 }
                 else {
                     results.testString(e, p, rest, absolute);
@@ -270,13 +282,14 @@ class Processor {
                 /* c8 ignore stop */
                 this.subwalks.add(ep, rest);
             }
-            else if (rp instanceof RegExp) {
-                this.testRegExp(e, rp, rest.rest(), absolute);
+            else if (typeof rp === 'object') {
+                this.testMatcher(e, rp, rest.rest(), absolute);
             }
         }
     }
-    testRegExp(e, p, rest, absolute) {
-        if (!p.test(e.name))
+    testMatcher(e, p, rest, absolute) {
+        // an entry name is one path portion, with no `/`
+        if (!p.testUnchecked(e.name))
             return;
         if (!rest) {
             this.matches.add(e, absolute, false);
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.js.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.js.map
index 58a70882e9462f7c0746a03edf0fe37e625230ce..6dd49347bbae161d08fad89e6200477b2575e79e 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/processor.js.map
@@ -1 +1 @@
-{"version":3,"file":"processor.js","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":";AAAA,qEAAqE;;;AAErE,yCAA8C;AAK9C;;GAEG;AACH,MAAa,cAAc;IACzB,KAAK,CAA0B;IAC/B,YAAY,QAAkC,IAAI,GAAG,EAAE;QACrD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IACD,IAAI;QACF,OAAO,IAAI,cAAc,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,CAAC;IACD,SAAS,CAAC,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E,OAAM;QAC3B,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;IAED,UAAU,CAAC,CAAO,EAAE,CAAS,EAAE,IAAoB,EAAE,QAAiB;QACpE,uBAAuB;QACvB,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;YAAE,OAAM;QACzB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF;AA9ND,8BA8NC","sourcesContent":["// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"processor.js","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":";AAAA,qEAAqE;;;AAErE,yCAAoC;AAKpC;;;;;;;;;;;GAWG;AACH,MAAa,cAAc;IACzB,MAAM,CAAiB;IACvB,KAAK,CAA2B;IAChC,YAAY,MAAuB;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IACD,IAAI;QACF,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,CAAA;IACjC,CAAC;IACD,mEAAmE;IACnE,KAAK,CAAC,QAAgB;QACpB,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAA;QACrC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CA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CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;IAED,UAAU,CAAC,CAAO,EAAE,CAAS,EAAE,IAAoB,EAAE,QAAiB;QACpE,uBAAuB;QACvB,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;YAAE,OAAM;QACzB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF;AA/ND,8BA+NC","sourcesContent":["// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport type { MMMatcher, MMPattern, Pattern } from './pattern.js'\nimport type { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path, in\n * this walk step and the steps that led to it.\n *\n * A step only adds to it before it makes the caches for the next\n * steps, so a copy can look up the chain of caches before it, in\n * place of copying their entries. A pattern for a path that a cache\n * up the chain has already seen is added to that cache's set, so that\n * the other steps that share it see it too. Paths are keyed by their\n * full path, because path-scurry can make a new Path object for the\n * same path once its cache of children is full.\n */\nexport class HasWalkedCache {\n  parent?: HasWalkedCache\n  store?: Map>\n  constructor(parent?: HasWalkedCache) {\n    this.parent = parent\n  }\n  copy() {\n    return new HasWalkedCache(this)\n  }\n  // the set for the path in this cache, or the closest one before it\n  #find(fullpath: string): Set | undefined {\n    const set = this.store?.get(fullpath)\n    return set || !this.parent ? set : this.parent.#find(fullpath)\n  }\n\n  hasWalked(target: Path, pattern: Pattern) {\n    return !!this.#find(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.#find(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else\n      (this.store ??= new Map()).set(\n        fullpath,\n        new Set([pattern.globString()]),\n      )\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n * The store maps each path to {@link MatchRecord.ABSOLUTE} and\n * {@link MatchRecord.IF_DIR} flags.\n */\nexport class MatchRecord {\n  static readonly ABSOLUTE = 2\n  static readonly IF_DIR = 1\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n =\n      (absolute ? MatchRecord.ABSOLUTE : 0) |\n      (ifDir ? MatchRecord.IF_DIR : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (typeof p === 'object') {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (typeof p === 'object') {\n          results.testMatcher(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (typeof rp === 'object') {\n        this.testMatcher(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testMatcher(\n    e: Path,\n    p: MMMatcher,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    // an entry name is one path portion, with no `/`\n    if (!p.testUnchecked(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.d.ts b/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.d.ts
index 499c8f4933857a8720e77b7b96d9842bbd3248ae..120871e839fd7a4f004aa4415fd80c10142c9656 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.d.ts
@@ -5,18 +5,20 @@
  * @module
  */
 import { Minipass } from 'minipass';
-import { Path } from 'path-scurry';
-import { IgnoreLike } from './ignore.js';
-import { Pattern } from './pattern.js';
+import type { Form } from 'minimatch';
+import type { Path } from 'path-scurry';
+import type { IgnoreLike } from './ignore.js';
+import type { Pattern } from './pattern.js';
 import { Processor } from './processor.js';
 export interface GlobWalkerOpts {
     absolute?: boolean;
     allowWindowsEscape?: boolean;
+    braceExpandMax?: number;
     cwd?: string | URL;
     dot?: boolean;
     dotRelative?: boolean;
     follow?: boolean;
-    ignore?: string | string[] | IgnoreLike;
+    ignore?: string | string[] | IgnoreLike | ReadonlyArray;
     mark?: boolean;
     matchBase?: boolean;
     maxDepth?: number;
@@ -25,6 +27,7 @@ export interface GlobWalkerOpts {
     nodir?: boolean;
     noext?: boolean;
     noglobstar?: boolean;
+    normalize?: boolean | Form;
     platform?: NodeJS.Platform;
     posix?: boolean;
     realpath?: boolean;
@@ -45,7 +48,7 @@ export type GWOFileTypesUnset = GlobWalkerOpts & {
     withFileTypes?: undefined;
 };
 export type Result = O extends GWOFileTypesTrue ? Path : O extends GWOFileTypesFalse ? string : O extends GWOFileTypesUnset ? string : Path | string;
-export type Matches = O extends GWOFileTypesTrue ? Set : O extends GWOFileTypesFalse ? Set : O extends GWOFileTypesUnset ? Set : Set;
+export type Matches = O extends GWOFileTypesTrue ? Path[] : O extends GWOFileTypesFalse ? string[] : O extends GWOFileTypesUnset ? string[] : (Path | string)[];
 export type MatchStream = Minipass, Result>;
 /**
  * basic walking utilities that all the glob walker types use
@@ -64,28 +67,28 @@ export declare abstract class GlobUtil any): void;
-    matchCheck(e: Path, ifDir: boolean): Promise;
+    onResume(fn: () => unknown): void;
+    matchCheck(inPath: Path, ifDir: boolean): Promise;
     matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined;
-    matchCheckSync(e: Path, ifDir: boolean): Path | undefined;
+    matchCheckSync(inPath: Path, ifDir: boolean): Path | undefined;
     abstract matchEmit(p: Result): void;
     abstract matchEmit(p: string | Path): void;
     matchFinish(e: Path, absolute: boolean): void;
     match(e: Path, absolute: boolean, ifDir: boolean): Promise;
     matchSync(e: Path, absolute: boolean, ifDir: boolean): void;
-    walkCB(target: Path, patterns: Pattern[], cb: () => any): void;
-    walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any;
-    walkCB3(target: Path, entries: Path[], processor: Processor, cb: () => any): void;
-    walkCBSync(target: Path, patterns: Pattern[], cb: () => any): void;
-    walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any;
-    walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => any): void;
+    walkCB(target: Path, patterns: Pattern[], cb: () => unknown): unknown;
+    walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => unknown): unknown;
+    walkCB3(target: Path, entries: Path[], processorx: Processor, cb: () => unknown): void;
+    walkCBSync(target: Path, patterns: Pattern[], cb: () => unknown): unknown;
+    walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => unknown): unknown;
+    walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => unknown): void;
 }
 export declare class GlobWalker extends GlobUtil {
-    matches: Set>;
+    matches: Result[];
     constructor(patterns: Pattern[], path: Path, opts: O);
     matchEmit(e: Result): void;
-    walk(): Promise>>;
-    walkSync(): Set>;
+    walk(): Promise[]>;
+    walkSync(): Result[];
 }
 export declare class GlobStream extends GlobUtil {
     results: Minipass, Result>;
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.d.ts.map
index 769957bd59bb1ce67cdf28134be59ca86946c405..8fe892e33fb0f4985939cb08d18cf12e47852eac 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.d.ts.map
@@ -1 +1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IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAUpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAK7B,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC;IAYxB,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC;CAO7B"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.js b/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.js
index cb15946d9a852cf8147b2c53f4021c796df36ef9..a3ac9574bd733e70705185a1b303cc677b52039b 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.js
@@ -10,8 +10,9 @@ exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0;
 const minipass_1 = require("minipass");
 const ignore_js_1 = require("./ignore.js");
 const processor_js_1 = require("./processor.js");
-const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts)
-    : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts)
+const { ABSOLUTE, IF_DIR } = processor_js_1.MatchRecord;
+const makeIgnore = (ignore, opts, cwd) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts, cwd)
+    : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts, cwd)
         : ignore;
 /**
  * basic walking utilities that all the glob walker types use
@@ -36,7 +37,7 @@ class GlobUtil {
         this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
         this.includeChildMatches = opts.includeChildMatches !== false;
         if (opts.ignore || !this.includeChildMatches) {
-            this.#ignore = makeIgnore(opts.ignore ?? [], opts);
+            this.#ignore = makeIgnore(opts.ignore ?? [], opts, path);
             if (!this.includeChildMatches &&
                 typeof this.#ignore.add !== 'function') {
                 const m = 'cannot ignore child matches, ignore lacks add() method.';
@@ -77,8 +78,6 @@ class GlobUtil {
         }
     }
     onResume(fn) {
-        if (this.signal?.aborted)
-            return;
         /* c8 ignore start */
         if (!this.paused) {
             fn();
@@ -90,16 +89,20 @@ class GlobUtil {
     }
     // do the requisite realpath/stat checking, and return the path
     // to add or undefined to filter it out.
-    async matchCheck(e, ifDir) {
+    async matchCheck(inPath, ifDir) {
         if (ifDir && this.opts.nodir)
             return undefined;
         let rpc;
+        let e;
         if (this.opts.realpath) {
-            rpc = e.realpathCached() || (await e.realpath());
+            rpc = inPath.realpathCached() || (await inPath.realpath());
             if (!rpc)
                 return undefined;
             e = rpc;
         }
+        else {
+            e = inPath;
+        }
         const needStat = e.isUnknown() || this.opts.stat;
         const s = needStat ? await e.lstat() : e;
         if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
@@ -125,16 +128,20 @@ class GlobUtil {
             e
             : undefined;
     }
-    matchCheckSync(e, ifDir) {
+    matchCheckSync(inPath, ifDir) {
         if (ifDir && this.opts.nodir)
             return undefined;
         let rpc;
+        let e;
         if (this.opts.realpath) {
-            rpc = e.realpathCached() || e.realpathSync();
+            rpc = inPath.realpathCached() || inPath.realpathSync();
             if (!rpc)
                 return undefined;
             e = rpc;
         }
+        else {
+            e = inPath;
+        }
         const needStat = e.isUnknown() || this.opts.stat;
         const s = needStat ? e.lstatSync() : e;
         if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
@@ -148,6 +155,10 @@ class GlobUtil {
     matchFinish(e, absolute) {
         if (this.#ignored(e))
             return;
+        this.#matchEmitChecked(e, absolute);
+    }
+    // emit a match that is known to not be seen or ignored yet
+    #matchEmitChecked(e, absolute) {
         // we know we have an ignore if this is false, but TS doesn't
         if (!this.includeChildMatches && this.#ignore?.add) {
             const ign = `${e.relativePosix()}/**`;
@@ -166,10 +177,10 @@ class GlobUtil {
         }
         else {
             const rel = this.opts.posix ? e.relativePosix() : e.relative();
-            const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
-                '.' + this.#sep
+            const pre = this.opts.dotRelative && !rel.startsWith(`..${this.#sep}`) ?
+                `.${this.#sep}`
                 : '';
-            this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
+            this.matchEmit(!rel ? `.${mark}` : pre + rel + mark);
         }
     }
     async match(e, absolute, ifDir) {
@@ -178,14 +189,16 @@ class GlobUtil {
             this.matchFinish(p, absolute);
     }
     matchSync(e, absolute, ifDir) {
+        // matchCheckSync just checked that it is not seen or ignored, and
+        // nothing can have changed since
         const p = this.matchCheckSync(e, ifDir);
         if (p)
-            this.matchFinish(p, absolute);
+            this.#matchEmitChecked(p, absolute);
     }
     walkCB(target, patterns, cb) {
         /* c8 ignore start */
         if (this.signal?.aborted)
-            cb();
+            return cb();
         /* c8 ignore stop */
         this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb);
     }
@@ -193,7 +206,7 @@ class GlobUtil {
         if (this.#childrenIgnored(target))
             return cb();
         if (this.signal?.aborted)
-            cb();
+            return cb();
         if (this.paused) {
             this.onResume(() => this.walkCB2(target, patterns, processor, cb));
             return;
@@ -207,11 +220,11 @@ class GlobUtil {
             if (--tasks === 0)
                 cb();
         };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+        for (const [m, n] of processor.matches.store) {
             if (this.#ignored(m))
                 continue;
             tasks++;
-            this.match(m, absolute, ifDir).then(() => next());
+            void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() => next());
         }
         for (const t of processor.subwalkTargets()) {
             if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
@@ -227,29 +240,29 @@ class GlobUtil {
         }
         next();
     }
-    walkCB3(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
+    walkCB3(target, entries, processorx, cb) {
+        const proc = processorx.filterEntries(target, entries);
         let tasks = 1;
         const next = () => {
             if (--tasks === 0)
                 cb();
         };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+        for (const [m, n] of proc.matches.store) {
             if (this.#ignored(m))
                 continue;
             tasks++;
-            this.match(m, absolute, ifDir).then(() => next());
+            void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() => next());
         }
-        for (const [target, patterns] of processor.subwalks.entries()) {
+        for (const [target, patterns] of proc.subwalks.entries()) {
             tasks++;
-            this.walkCB2(target, patterns, processor.child(), next);
+            this.walkCB2(target, patterns, proc.child(), next);
         }
         next();
     }
     walkCBSync(target, patterns, cb) {
         /* c8 ignore start */
         if (this.signal?.aborted)
-            cb();
+            return cb();
         /* c8 ignore stop */
         this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb);
     }
@@ -257,7 +270,7 @@ class GlobUtil {
         if (this.#childrenIgnored(target))
             return cb();
         if (this.signal?.aborted)
-            cb();
+            return cb();
         if (this.paused) {
             this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
             return;
@@ -271,10 +284,10 @@ class GlobUtil {
             if (--tasks === 0)
                 cb();
         };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+        for (const [m, n] of processor.matches.store) {
             if (this.#ignored(m))
                 continue;
-            this.matchSync(m, absolute, ifDir);
+            this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR));
         }
         for (const t of processor.subwalkTargets()) {
             if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
@@ -287,32 +300,34 @@ class GlobUtil {
         next();
     }
     walkCB3Sync(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
+        const proc = processor.filterEntries(target, entries);
         let tasks = 1;
         const next = () => {
             if (--tasks === 0)
                 cb();
         };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+        for (const [m, n] of proc.matches.store) {
             if (this.#ignored(m))
                 continue;
-            this.matchSync(m, absolute, ifDir);
+            this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR));
         }
-        for (const [target, patterns] of processor.subwalks.entries()) {
+        for (const [target, patterns] of proc.subwalks.entries()) {
             tasks++;
-            this.walkCB2Sync(target, patterns, processor.child(), next);
+            this.walkCB2Sync(target, patterns, proc.child(), next);
         }
         next();
     }
 }
 exports.GlobUtil = GlobUtil;
 class GlobWalker extends GlobUtil {
-    matches = new Set();
+    // each Path is only emitted once (see GlobUtil.seen), so the results
+    // do not need to be deduped
+    matches = [];
     constructor(patterns, path, opts) {
         super(patterns, path, opts);
     }
     matchEmit(e) {
-        this.matches.add(e);
+        this.matches.push(e);
     }
     async walk() {
         if (this.signal?.aborted)
@@ -366,7 +381,7 @@ class GlobStream extends GlobUtil {
     stream() {
         const target = this.path;
         if (target.isUnknown()) {
-            target.lstat().then(() => {
+            void target.lstat().then(() => {
                 this.walkCB(target, this.patterns, () => this.results.end());
             });
         }
diff --git a/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.js.map b/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.js.map
index 49b013864d534bfba5b0357f69223f32f4ffd37b..d88ff08fff93ec2b5bce7568eb970de4f6d9f999 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/commonjs/walker.js.map
@@ -1 +1 @@
-{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,uCAAmC;AAEnC,2CAAgD;AAQhD,iDAA0C;AA0D1C,MAAM,UAAU,GAAG,CACjB,MAAsC,EACtC,IAAoB,EACR,EAAE,CACd,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,kBAAM,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC;IACvD,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,kBAAM,CAAC,MAAM,EAAE,IAAI,CAAC;QAClD,CAAC,CAAC,MAAM,CAAA;AAEV;;GAEG;AACH,MAAsB,QAAQ;IAC5B,IAAI,CAAM;IACV,QAAQ,CAAW;IACnB,IAAI,CAAG;IACP,IAAI,GAAc,IAAI,GAAG,EAAQ,CAAA;IACjC,MAAM,GAAY,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IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;YAC9D,CAAC,CAAC,CAAA;QACJ,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QAC9D,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,UAAU;QACR,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF;AAvCD,gCAuCC","sourcesContent":["/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Set\n  : O extends GWOFileTypesFalse ? Set\n  : O extends GWOFileTypesUnset ? Set\n  : Set\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts)\n  : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n          '.' + this.#sep\n        : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  matches = new Set>()\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise>> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Set> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,uCAAmC;AAInC,2CAAoC;AAQpC,iDAAuD;AAEvD,MAAM,EAAE,QAAQ,EAAE,MAAM,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AI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QAC9D,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,UAAU;QACR,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF;AAvCD,gCAuCC","sourcesContent":["/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport type { Form } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport type { IgnoreLike } from './ignore.js'\nimport { Ignore } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport type { Pattern } from './pattern.js'\nimport { MatchRecord, Processor } from './processor.js'\n\nconst { ABSOLUTE, IF_DIR } = MatchRecord\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  braceExpandMax?: number\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike | ReadonlyArray\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  normalize?: boolean | Form\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Path[]\n  : O extends GWOFileTypesFalse ? string[]\n  : O extends GWOFileTypesUnset ? string[]\n  : (Path | string)[]\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike | ReadonlyArray,\n  opts: GlobWalkerOpts,\n  cwd: Path,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts, cwd)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts, cwd)\n  : (ignore as IgnoreLike)\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => unknown)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts, path)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => unknown) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => unknown) {\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(\n    inPath: Path,\n    ifDir: boolean,\n  ): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    let e: Path\n    if (this.opts.realpath) {\n      rpc = inPath.realpathCached() || (await inPath.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    } else {\n      e = inPath\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(inPath: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    let e: Path\n    if (this.opts.realpath) {\n      rpc = inPath.realpathCached() || inPath.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    } else {\n      e = inPath\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    this.#matchEmitChecked(e, absolute)\n  }\n\n  // emit a match that is known to not be seen or ignored yet\n  #matchEmitChecked(e: Path, absolute: boolean) {\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith(`..${this.#sep}`) ?\n          `.${this.#sep}`\n        : ''\n      this.matchEmit(!rel ? `.${mark}` : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    // matchCheckSync just checked that it is not seen or ignored, and\n    // nothing can have changed since\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.#matchEmitChecked(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => unknown) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) return cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of processor.matches.store) {\n      if (this.#ignored(m)) continue\n      tasks++\n      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>\n        next(),\n      )\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processorx: Processor,\n    cb: () => unknown,\n  ) {\n    const proc = processorx.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of proc.matches.store) {\n      if (this.#ignored(m)) continue\n      tasks++\n      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>\n        next(),\n      )\n    }\n    for (const [target, patterns] of proc.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, proc.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => unknown) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) return cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of processor.matches.store) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    const proc = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of proc.matches.store) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))\n    }\n    for (const [target, patterns] of proc.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, proc.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  // each Path is only emitted once (see GlobUtil.seen), so the results\n  // do not need to be deduped\n  matches: Result[] = []\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.push(e)\n  }\n\n  async walk(): Promise[]> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Result[] {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      void target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/glob.d.ts b/mac/patchers/desktop/node_modules/glob/dist/esm/glob.d.ts
index 85c1ccc263e7d3fb4685a50ff6b3531299246bd7..db4231afbb78ba7ed7988cbe30639ac1864e7e02 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/glob.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/glob.d.ts
@@ -1,7 +1,9 @@
+import type { Form } from 'minimatch';
 import { Minimatch } from 'minimatch';
-import { Minipass } from 'minipass';
-import { FSOption, Path, PathScurry } from 'path-scurry';
-import { IgnoreLike } from './ignore.js';
+import type { Minipass } from 'minipass';
+import type { FSOption, Path } from 'path-scurry';
+import { PathScurry } from 'path-scurry';
+import type { IgnoreLike } from './ignore.js';
 import { Pattern } from './pattern.js';
 export type MatchSet = Minimatch['set'];
 export type GlobParts = Exclude;
@@ -43,7 +45,7 @@ export interface GlobOptions {
      * The current working directory in which to search. Defaults to
      * `process.cwd()`.
      *
-     * May be eiher a string path or a `file://` URL object or string.
+     * May be either a string path or a `file://` URL object or string.
      */
     cwd?: string | URL;
     /**
@@ -89,7 +91,7 @@ export interface GlobOptions {
      * determine whether any Path is a match or if its children should be
      * traversed, respectively.
      */
-    ignore?: string | string[] | IgnoreLike;
+    readonly ignore?: string | string[] | IgnoreLike | ReadonlyArray;
     /**
      * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no
      * effect if {@link nobrace} is set.
@@ -139,6 +141,18 @@ export interface GlobOptions {
      * Do not match "extglob" patterns such as `+(a|b)`.
      */
     noext?: boolean;
+    /**
+     * Normalize unicode in the pattern, and in the file names that it is
+     * matched against, with this form: `'NFC'`, `'NFD'`, `'NFKC'`, or
+     * `'NFKD'`. `true` means `'NFC'`. This is passed to minimatch, so it
+     * applies to the portions of the pattern with magic, and to the
+     * `ignore` patterns.
+     *
+     * The portions of the pattern without magic are looked up with
+     * path-scurry, which already compares the names of the entries
+     * that it knows in their `'NFKD'` form.
+     */
+    normalize?: boolean | Form;
     /**
      * Do not match `**` against multiple filenames. (Ie, treat it as a normal
      * `*` instead.)
@@ -232,11 +246,6 @@ export interface GlobOptions {
      * http://npm.im/path-scurry for details about what can be overridden.
      */
     fs?: FSOption;
-    /**
-     * Just passed along to Minimatch.  Note that this makes all pattern
-     * matching operations slower and *extremely* noisy.
-     */
-    debug?: boolean;
     /**
      * Return `/` delimited paths, even on Windows.
      *
@@ -324,7 +333,7 @@ export declare class Glob implements GlobOptions {
     dot: boolean;
     dotRelative: boolean;
     follow: boolean;
-    ignore?: string | string[] | IgnoreLike;
+    ignore?: string | string[] | IgnoreLike | ReadonlyArray;
     magicalBraces: boolean;
     mark?: boolean;
     matchBase: boolean;
@@ -334,7 +343,7 @@ export declare class Glob implements GlobOptions {
     nodir: boolean;
     noext: boolean;
     noglobstar: boolean;
-    pattern: string[];
+    pattern: string[] | ReadonlyArray;
     platform: NodeJS.Platform;
     realpath: boolean;
     scurry: PathScurry;
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/glob.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/esm/glob.d.ts.map
index b8d3c2596f067096f22a3bd1b59640fdd039c52c..19b6000016c53e84baef66073ed69ec68c6c418f 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/glob.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/glob.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AACvD,OAAO,EAA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,CAAA;IACjB,MAAM,EAAE,UAAU,CAAA;IAClB,IAAI,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,oBAAoB,EAAE,OAAO,CAAA;IAC7B,aAAa,EAAE,SAAS,CAAC,IAAI,CAAC,CAAA;IAC9B,mBAAmB,EAAE,OAAO,CAAA;IAE5B;;OAEG;IACH,IAAI,EAAE,IAAI,CAAA;IAEV;;OAEG;IACH,QAAQ,EAAE,OAAO,EAAE,CAAA;IAEnB;;;;;;;;;;;OAWG;gBACS,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI;IAyHlD;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAkBpC;;OAEG;IACH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAczB;;OAEG;IACH,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAc9C;;OAEG;IACH,UAAU,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAclD;;;OAGG;IACH,WAAW,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGlD,CAAC,MAAM,CAAC,QAAQ,CAAC;IAIjB;;;OAGG;IACH,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGnD,CAAC,MAAM,CAAC,aAAa,CAAC;CAGvB"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/glob.js b/mac/patchers/desktop/node_modules/glob/dist/esm/glob.js
index d89c3dad90daa8423bf22ba4df006e9fb6a4fb4c..a72da9a0cda0722385cac29ad96d9d42e299ac48 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/glob.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/glob.js
@@ -94,23 +94,21 @@ export class Glob {
         if (this.withFileTypes && this.absolute !== undefined) {
             throw new Error('cannot set absolute and withFileTypes:true');
         }
-        if (typeof pattern === 'string') {
-            pattern = [pattern];
-        }
+        let p = typeof pattern === 'string' ? [pattern] : pattern;
         this.windowsPathsNoEscape =
             !!opts.windowsPathsNoEscape ||
                 opts.allowWindowsEscape ===
                     false;
         if (this.windowsPathsNoEscape) {
-            pattern = pattern.map(p => p.replace(/\\/g, '/'));
+            p = p.map(p => p.replace(/\\/g, '/'));
         }
         if (this.matchBase) {
             if (opts.noglobstar) {
                 throw new TypeError('base matching requires globstar');
             }
-            pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`));
+            p = p.map(p => (p.includes('/') ? p : `./**/${p}`));
         }
-        this.pattern = pattern;
+        this.pattern = p;
         this.platform = opts.platform || defaultPlatform;
         this.opts = { ...opts, platform: this.platform };
         if (opts.scurry) {
@@ -151,7 +149,6 @@ export class Glob {
             optimizationLevel: 2,
             platform: this.platform,
             windowsPathsNoEscape: this.windowsPathsNoEscape,
-            debug: !!this.opts.debug,
         };
         const mms = this.pattern.map(p => new Minimatch(p, mmo));
         const [matchSet, globParts] = mms.reduce((set, m) => {
@@ -173,30 +170,26 @@ export class Glob {
         // coerce them into the right shape.  It will have already called
         // realpath() if the option was set to do so, so we know that's cached.
         // start out knowing the cwd, at least
-        return [
-            ...(await new GlobWalker(this.patterns, this.scurry.cwd, {
-                ...this.opts,
-                maxDepth: this.maxDepth !== Infinity ?
-                    this.maxDepth + this.scurry.cwd.depth()
-                    : Infinity,
-                platform: this.platform,
-                nocase: this.nocase,
-                includeChildMatches: this.includeChildMatches,
-            }).walk()),
-        ];
+        return await new GlobWalker(this.patterns, this.scurry.cwd, {
+            ...this.opts,
+            maxDepth: this.maxDepth !== Infinity ?
+                this.maxDepth + this.scurry.cwd.depth()
+                : Infinity,
+            platform: this.platform,
+            nocase: this.nocase,
+            includeChildMatches: this.includeChildMatches,
+        }).walk();
     }
     walkSync() {
-        return [
-            ...new GlobWalker(this.patterns, this.scurry.cwd, {
-                ...this.opts,
-                maxDepth: this.maxDepth !== Infinity ?
-                    this.maxDepth + this.scurry.cwd.depth()
-                    : Infinity,
-                platform: this.platform,
-                nocase: this.nocase,
-                includeChildMatches: this.includeChildMatches,
-            }).walkSync(),
-        ];
+        return new GlobWalker(this.patterns, this.scurry.cwd, {
+            ...this.opts,
+            maxDepth: this.maxDepth !== Infinity ?
+                this.maxDepth + this.scurry.cwd.depth()
+                : Infinity,
+            platform: this.platform,
+            nocase: this.nocase,
+            includeChildMatches: this.includeChildMatches,
+        }).walkSync();
     }
     stream() {
         return new GlobStream(this.patterns, this.scurry.cwd, {
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/glob.js.map b/mac/patchers/desktop/node_modules/glob/dist/esm/glob.js.map
index fa2cfcd0859d98c18da8c49164edcfbe8e15267d..cf71b744cb924b309b08fb80fe5004544c055046 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/glob.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/glob.js.map
@@ -1 +1 @@
-{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AAEvD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAGL,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,aAAa,CAAA;AAEpB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAKpD,4CAA4C;AAC5C,gDAAgD;AAChD,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAA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A;IACb,CAAC;IAMD,UAAU;QACR,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACpD,GAAG,IAAI,CAAC,IAAI;YACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,UAAU,EAAE,CAAA;IACjB,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF","sourcesContent":["import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n  FSOption,\n  Path,\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be eiher a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignored` and `childrenIgnored`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  ignore?: string | string[] | IgnoreLike\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Just passed along to Minimatch.  Note that this makes all pattern\n   * matching operations slower and *extremely* noisy.\n   */\n  debug?: boolean\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n\n  /**\n   * max number of `{...}` patterns to expand. Default `1_000`.\n   *\n   * Note: this is much less than minimatch's default of `100_000`,\n   * because Glob has higher memory requirements due to walking\n   * the file system tree.\n   */\n  braceExpandMax?: number\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[]\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    if (typeof pattern === 'string') {\n      pattern = [pattern]\n    }\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = pattern\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      braceExpandMax: 10_000,\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      // default nocase based on platform\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n      debug: !!this.opts.debug,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return [\n      ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walk()),\n    ]\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return [\n      ...new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walkSync(),\n    ]\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAErC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,aAAa,CAAA;AAEpB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAKpD,4CAA4C;AAC5C,gDAAgD;AAChD,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAyWX;;GAEG;AACH,MAAM,OAAO,IAAI;IACf,QAAQ,CAAU;IAClB,GAAG,CAAQ;IACX,IAAI,CAAS;IACb,GAAG,CAAS;IACZ,WAAW,CAAS;I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;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,UAAU,EAAE,CAAA;IACjB,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF","sourcesContent":["import type { Form, MinimatchOptions } from 'minimatch'\nimport { Minimatch } from 'minimatch'\nimport type { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport type { FSOption, Path } from 'path-scurry'\nimport {\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport type { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be either a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignored` and `childrenIgnored`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  readonly ignore?: string | string[] | IgnoreLike | ReadonlyArray\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Normalize unicode in the pattern, and in the file names that it is\n   * matched against, with this form: `'NFC'`, `'NFD'`, `'NFKC'`, or\n   * `'NFKD'`. `true` means `'NFC'`. This is passed to minimatch, so it\n   * applies to the portions of the pattern with magic, and to the\n   * `ignore` patterns.\n   *\n   * The portions of the pattern without magic are looked up with\n   * path-scurry, which already compares the names of the entries\n   * that it knows in their `'NFKD'` form.\n   */\n  normalize?: boolean | Form\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n\n  /**\n   * max number of `{...}` patterns to expand. Default `1_000`.\n   *\n   * Note: this is much less than minimatch's default of `100_000`,\n   * because Glob has higher memory requirements due to walking\n   * the file system tree.\n   */\n  braceExpandMax?: number\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike | ReadonlyArray\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[] | ReadonlyArray\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    let p: string[] = typeof pattern === 'string' ? [pattern] : pattern\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      p = p.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      p = p.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = p\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      braceExpandMax: 10_000,\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      // default nocase based on platform\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return await new GlobWalker(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).walk()\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return new GlobWalker(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).walkSync()\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.d.ts b/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.d.ts
index 8aec3bd9725175d9c72be14476fea2a117ca8b09..a152a0985717648c2dc1be586ca2471474b91968 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.d.ts
@@ -1,4 +1,4 @@
-import { GlobOptions } from './glob.js';
+import type { GlobOptions } from './glob.js';
 /**
  * Return true if the patterns provided contain any magic glob characters,
  * given the options provided.
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.d.ts.map
index e2f7e449672a5f671e82090a226ded1ccad56c1d..c916528fa393fc8e3ccb7af4ffffaf96a29084d1 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,GACnB,SAAS,MAAM,GAAG,MAAM,EAAE,EAC1B,UAAS,WAAgB,KACxB,OAQF,CAAA"}
\ No newline at end of file
+{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAE5C;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,GACnB,SAAS,MAAM,GAAG,MAAM,EAAE,EAC1B,UAAS,WAAgB,KACxB,OAKF,CAAA"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.js b/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.js
index ba2321ab868d025d56e2ce360c0c02e3e622e6b8..d89822649c3a2d3cd3891a52718d53dad83a110e 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.js
@@ -11,10 +11,7 @@ import { Minimatch } from 'minimatch';
  * is in the options, brace expansion _is_ treated as a pattern having magic.
  */
 export const hasMagic = (pattern, options = {}) => {
-    if (!Array.isArray(pattern)) {
-        pattern = [pattern];
-    }
-    for (const p of pattern) {
+    for (const p of Array.isArray(pattern) ? pattern : [pattern]) {
         if (new Minimatch(p, options).hasMagic())
             return true;
     }
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.js.map b/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.js.map
index a20f5aa2e0fdb50071ab84db31b1993d2f220253..5860fe42a939b15ac0a205a814728660a6dde756 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/has-magic.js.map
@@ -1 +1 @@
-{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAGrC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,IAAI,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  if (!Array.isArray(pattern)) {\n    pattern = [pattern]\n  }\n  for (const p of pattern) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAGrC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,KAAK,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7D,IAAI,IAAI,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["import { Minimatch } from 'minimatch'\nimport type { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  for (const p of Array.isArray(pattern) ? pattern : [pattern]) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.d.ts b/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.d.ts
index 1893b16df877c9b50c071ee7b066715f6e58c43e..59f0bdbb8fe637b5ba791474140b2ec27b74d52f 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.d.ts
@@ -1,6 +1,7 @@
-import { Minimatch, MinimatchOptions } from 'minimatch';
-import { Path } from 'path-scurry';
-import { GlobWalkerOpts } from './walker.js';
+import type { MinimatchOptions } from 'minimatch';
+import { Minimatch } from 'minimatch';
+import type { Path } from 'path-scurry';
+import type { GlobWalkerOpts } from './walker.js';
 export interface IgnoreLike {
     ignored?: (p: Path) => boolean;
     childrenIgnored?: (p: Path) => boolean;
@@ -16,7 +17,18 @@ export declare class Ignore implements IgnoreLike {
     absoluteChildren: Minimatch[];
     platform: NodeJS.Platform;
     mmopts: MinimatchOptions;
-    constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, platform, }: GlobWalkerOpts);
+    /**
+     * The escaped glob for the directory that a pattern starting with
+     * `/` is rooted at, with no trailing `/`.
+     */
+    slashRoot: string;
+    /**
+     * Patterns that start with `/` (but not drive letters or UNC paths
+     * on Windows) start at the `root` option if it is set, or else at
+     * the root of `cwd`, the same as non-ignored patterns. If `cwd` is
+     * not provided, they start at `/`.
+     */
+    constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, normalize, platform, root, windowsPathsNoEscape, allowWindowsEscape, braceExpandMax, }: GlobWalkerOpts, cwd?: Path);
     add(ign: string): void;
     ignored(p: Path): boolean;
     childrenIgnored(p: Path): boolean;
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.d.ts.map
index 57d6ab6153d770397a5acb7881ccf52a048dee89..7be6090bed2836ff447303b85bc1168bb9afa0e6 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;A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AE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;IACxB;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAA;IAEjB;;;;;OAKG;gBAED,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,SAAS,EACT,QAA0B,EAC1B,IAAI,EACJ,oBAAoB,EACpB,kBAAkB,EAClB,cAAuB,GACxB,EAAE,cAAc,EACjB,GAAG,CAAC,EAAE,IAAI;IA+BZ,GAAG,CAAC,GAAG,EAAE,MAAM;IA6Cf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.js b/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.js
index 539c4a4fdebc4b036e5ca02060eae76572e5622d..2ce6c425555cfcfdfb425cdd9aa4319807569f2d 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.js
@@ -2,7 +2,7 @@
 // a given path should be ignored.
 // Ignoring a path ignores its children if the pattern ends in /**
 // Ignores are always parsed in dot:true mode
-import { Minimatch } from 'minimatch';
+import { escape, Minimatch } from 'minimatch';
 import { Pattern } from './pattern.js';
 const defaultPlatform = (typeof process === 'object' &&
     process &&
@@ -19,23 +19,41 @@ export class Ignore {
     absoluteChildren;
     platform;
     mmopts;
-    constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) {
+    /**
+     * The escaped glob for the directory that a pattern starting with
+     * `/` is rooted at, with no trailing `/`.
+     */
+    slashRoot;
+    /**
+     * Patterns that start with `/` (but not drive letters or UNC paths
+     * on Windows) start at the `root` option if it is set, or else at
+     * the root of `cwd`, the same as non-ignored patterns. If `cwd` is
+     * not provided, they start at `/`.
+     */
+    constructor(ignored, { nobrace, nocase, noext, noglobstar, normalize, platform = defaultPlatform, root, windowsPathsNoEscape, allowWindowsEscape, braceExpandMax = 10_000, }, cwd) {
         this.relative = [];
         this.absolute = [];
         this.relativeChildren = [];
         this.absoluteChildren = [];
         this.platform = platform;
+        windowsPathsNoEscape =
+            !!windowsPathsNoEscape || allowWindowsEscape === false;
         this.mmopts = {
+            braceExpandMax,
             dot: true,
             nobrace,
             nocase,
             noext,
             noglobstar,
+            normalize,
             optimizationLevel: 2,
             platform,
             nocomment: true,
             nonegate: true,
+            windowsPathsNoEscape,
         };
+        const slashRoot = cwd?.resolve(root ?? '/').fullpath() ?? '/';
+        this.slashRoot = escape(slashRoot.replace(/\\/g, '/').replace(/\/$/, ''), { magicalBraces: true, windowsPathsNoEscape });
         for (const ign of ignored)
             this.add(ign);
     }
@@ -68,7 +86,10 @@ export class Ignore {
             }
             /* c8 ignore stop */
             const p = new Pattern(parsed, globParts, 0, this.platform);
-            const m = new Minimatch(p.globString(), this.mmopts);
+            const glob = p.root() === '/' ?
+                `${this.slashRoot}/${p.rest()?.globString() ?? ''}`
+                : p.globString();
+            const m = new Minimatch(glob, this.mmopts);
             const children = globParts[globParts.length - 1] === '**';
             const absolute = p.isAbsolute();
             if (absolute)
@@ -99,8 +120,8 @@ export class Ignore {
         return false;
     }
     childrenIgnored(p) {
-        const fullpath = p.fullpath() + '/';
-        const relative = (p.relative() || '.') + '/';
+        const fullpath = `${p.fullpath()}/`;
+        const relative = `${p.relative() || '.'}/`;
         for (const m of this.relativeChildren) {
             if (m.match(relative))
                 return true;
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.js.map b/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.js.map
index 2cddba2ecfe9f605f05b45ad1c23663de46945b8..0ab5378e491d8a5e0eb94b14fc668c32b6f67c54 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/ignore.js.map
+++ b/mac/patchers/desktop/node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,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF","sourcesContent":["// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      platform = defaultPlatform,\n    }: GlobWalkerOpts,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    this.mmopts = {\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n    }\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const m = new Minimatch(p.globString(), this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = p.fullpath() + '/'\n    const relative = (p.relative() || '.') + '/'\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"ignore.js","sourceRoot":"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,IAAI,GAAG,CAAA;QACpC,MAAM,SAAS,GAAG,GAAG,QAAQ,GAAG,CAAA;QAChC,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,eAAe,CAAC,CAAO;QACrB,MAAM,QAAQ,GAAG,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,CAAA;QACnC,MAAM,QAAQ,GAAG,GAAG,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,GAAG,CAAA;QAC1C,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF","sourcesContent":["// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport type { MinimatchOptions } from 'minimatch'\nimport { escape, Minimatch } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport type { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n  /**\n   * The escaped glob for the directory that a pattern starting with\n   * `/` is rooted at, with no trailing `/`.\n   */\n  slashRoot: string\n\n  /**\n   * Patterns that start with `/` (but not drive letters or UNC paths\n   * on Windows) start at the `root` option if it is set, or else at\n   * the root of `cwd`, the same as non-ignored patterns. If `cwd` is\n   * not provided, they start at `/`.\n   */\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      normalize,\n      platform = defaultPlatform,\n      root,\n      windowsPathsNoEscape,\n      allowWindowsEscape,\n      braceExpandMax = 10_000,\n    }: GlobWalkerOpts,\n    cwd?: Path,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    windowsPathsNoEscape =\n      !!windowsPathsNoEscape || allowWindowsEscape === false\n    this.mmopts = {\n      braceExpandMax,\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      normalize,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n      windowsPathsNoEscape,\n    }\n    const slashRoot = cwd?.resolve(root ?? '/').fullpath() ?? '/'\n    this.slashRoot = escape(\n      slashRoot.replace(/\\\\/g, '/').replace(/\\/$/, ''),\n      { magicalBraces: true, windowsPathsNoEscape },\n    )\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const glob =\n        p.root() === '/' ?\n          `${this.slashRoot}/${p.rest()?.globString() ?? ''}`\n        : p.globString()\n      const m = new Minimatch(glob, this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = `${p.fullpath()}/`\n    const relative = `${p.relative() || '.'}/`\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/index.d.ts b/mac/patchers/desktop/node_modules/glob/dist/esm/index.d.ts
index cb09bfb64acb34985b08e658882181a3fff9bd38..05abf240752bdc2256ccbb79efc4cca3694c4750 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/index.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/index.d.ts
@@ -1,8 +1,9 @@
-import { Minipass } from 'minipass';
-import { Path } from 'path-scurry';
+import type { Minipass } from 'minipass';
+import type { Path } from 'path-scurry';
 import type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset } from './glob.js';
 import { Glob } from './glob.js';
 export { escape, unescape } from 'minimatch';
+export type { Form } from 'minimatch';
 export type { FSOption, Path, WalkOptions, WalkOptionsWithFileTypesTrue, WalkOptionsWithFileTypesUnset, } from 'path-scurry';
 export { Glob } from './glob.js';
 export type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset, } from './glob.js';
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/index.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/esm/index.d.ts.map
index 5fb32252b63747526a971d82bf6ab2ee61b53631..f505cef301541868c7ca11eb5f2a8bfbdbe8fa4e 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/index.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/index.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,KAAK,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,EAC9B,MAAM,WAAW,CAAA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AAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACnC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACrC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AASxE,eAAO,MAAM,UAAU,uBAAiB,CAAA;AACxC,eAAO,MAAM,MAAM;;CAAsD,CAAA;AACzE,eAAO,MAAM,WAAW,wBAAkB,CAAA;AAC1C,eAAO,MAAM,OAAO;;CAElB,CAAA;AACF,eAAO,MAAM,IAAI;;;CAGf,CAAA;AAEF,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;CAgBf,CAAA"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/index.js.map b/mac/patchers/desktop/node_modules/glob/dist/esm/index.js.map
index a4f93dd0c1d87d292b2ce821897926fafeb582d4..8b00edf1ed125bd0afec38ae7e9796dec86e2cf3 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/index.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/index.js.map
@@ -1 +1 @@
-{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAS5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBA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AG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAA;AACzE,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAA;AAC1C,MAAM,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;IAChD,IAAI,EAAE,eAAe;CACtB,CAAC,CAAA;AACF,MAAM,CAAC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC1C,MAAM,EAAE,cAAc;IACtB,OAAO,EAAE,eAAe;CACzB,CAAC,CAAA;AAEF,MAAM,CAAC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,KAAK;IACX,QAAQ;IACR,IAAI;IACJ,UAAU;IACV,MAAM;IACN,cAAc;IACd,UAAU;IACV,WAAW;IACX,OAAO;IACP,eAAe;IACf,WAAW;IACX,IAAI;IACJ,QAAQ;IACR,MAAM;IACN,QAAQ;CACT,CAAC,CAAA;AACF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA","sourcesContent":["import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n"]}
\ No newline at end of file
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAS5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEzC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAS5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAOhC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAyBpC,MAAM,UAAU,cAAc,CAC5B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAA;AAChD,CAAC;AAsBD,MAAM,UAAU,UAAU,CACxB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,EAAE,CAAA;AAC5C,CAAC;AAqBD,MAAM,UAAU,QAAQ,CACtB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAA;AAC9C,CAA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AG,IAAI,CAAA","sourcesContent":["import { escape, unescape } from 'minimatch'\nimport type { Minipass } from 'minipass'\nimport type { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type { Form } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/index.min.js b/mac/patchers/desktop/node_modules/glob/dist/esm/index.min.js
index e6ea7cc1bc83118429b83ed4118878b803931371..4aa37645b7d639a9bce05b70310346aa8ae2b016 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/index.min.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/index.min.js
@@ -1,4 +1,3 @@
-var Gt=(n,t,e)=>{let s=n instanceof RegExp?ce(n,e):n,i=t instanceof RegExp?ce(t,e):t,r=s!==null&&i!=null&&ss(s,i,e);return r&&{start:r[0],end:r[1],pre:e.slice(0,r[0]),body:e.slice(r[0]+s.length,r[1]),post:e.slice(r[1]+i.length)}},ce=(n,t)=>{let e=t.match(n);return e?e[0]:null},ss=(n,t,e)=>{let s,i,r,o,h,a=e.indexOf(n),l=e.indexOf(t,a+1),u=a;if(a>=0&&l>0){if(n===t)return[a,l];for(s=[],r=e.length;u>=0&&!h;){if(u===a)s.push(u),a=e.indexOf(n,u+1);else if(s.length===1){let c=s.pop();c!==void 0&&(h=[c,l])}else i=s.pop(),i!==void 0&&i=0?a:l}s.length&&o!==void 0&&(h=[r,o])}return h};var fe="\0SLASH"+Math.random()+"\0",ue="\0OPEN"+Math.random()+"\0",qt="\0CLOSE"+Math.random()+"\0",de="\0COMMA"+Math.random()+"\0",pe="\0PERIOD"+Math.random()+"\0",is=new RegExp(fe,"g"),rs=new RegExp(ue,"g"),ns=new RegExp(qt,"g"),os=new RegExp(de,"g"),hs=new RegExp(pe,"g"),as=/\\\\/g,ls=/\\{/g,cs=/\\}/g,fs=/\\,/g,us=/\\./g,ds=1e5;function Ht(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function ps(n){return n.replace(as,fe).replace(ls,ue).replace(cs,qt).replace(fs,de).replace(us,pe)}function ms(n){return n.replace(is,"\\").replace(rs,"{").replace(ns,"}").replace(os,",").replace(hs,".")}function me(n){if(!n)return[""];let t=[],e=Gt("{","}",n);if(!e)return n.split(",");let{pre:s,body:i,post:r}=e,o=s.split(",");o[o.length-1]+="{"+i+"}";let h=me(r);return r.length&&(o[o.length-1]+=h.shift(),o.push.apply(o,h)),t.push.apply(t,o),t}function ge(n,t={}){if(!n)return[];let{max:e=ds}=t;return n.slice(0,2)==="{}"&&(n="\\{\\}"+n.slice(2)),ht(ps(n),e,!0).map(ms)}function gs(n){return"{"+n+"}"}function ws(n){return/^-?0\d/.test(n)}function ys(n,t){return n<=t}function bs(n,t){return n>=t}function ht(n,t,e){let s=[],i=Gt("{","}",n);if(!i)return[n];let r=i.pre,o=i.post.length?ht(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let h=0;h=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(n=i.pre+"{"+i.body+qt+i.post,ht(n,t,!0)):[n];let c;if(l)c=i.body.split(/\.\./);else if(c=me(i.body),c.length===1&&c[0]!==void 0&&(c=ht(c[0],t,!1).map(gs),c.length===1))return o.map(f=>i.pre+c[0]+f);let d;if(l&&c[0]!==void 0&&c[1]!==void 0){let f=Ht(c[0]),m=Ht(c[1]),p=Math.max(c[0].length,c[1].length),w=c.length===3&&c[2]!==void 0?Math.abs(Ht(c[2])):1,g=ys;m0){let $=new Array(z+1).join("0");y<0?b="-"+$+b.slice(1):b=$+b}}d.push(b)}}else{d=[];for(let f=0;f{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var Ss={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},lt=n=>n.replace(/[[\]\\-]/g,"\\$&"),Es=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),we=n=>n.join(""),ye=(n,t)=>{let e=t;if(n.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],i=[],r=e+1,o=!1,h=!1,a=!1,l=!1,u=e,c="";t:for(;rc?s.push(lt(c)+"-"+lt(p)):p===c&&s.push(lt(p)),c="",r++;continue}if(n.startsWith("-]",r+1)){s.push(lt(p+"-")),r+=2;continue}if(n.startsWith("-",r+1)){c=p,r+=2;continue}s.push(lt(p)),r++}if(ue?t?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?n.replace(/\[([^\/\\{}])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");var xs=new Set(["!","?","+","*","@"]),be=n=>xs.has(n),vs="(?!(?:^|/)\\.\\.?(?:$|/))",Ct="(?!\\.)",Cs=new Set(["[","."]),Ts=new Set(["..","."]),As=new Set("().*{}+?[]^$\\!"),ks=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Kt="[^/]",Se=Kt+"*?",Ee=Kt+"+?",Q=class n{type;#t;#s;#n=!1;#r=[];#o;#S;#w;#c=!1;#h;#u;#f=!1;constructor(t,e,s={}){this.type=t,t&&(this.#s=!0),this.#o=e,this.#t=this.#o?this.#o.#t:this,this.#h=this.#t===this?s:this.#t.#h,this.#w=this.#t===this?[]:this.#t.#w,t==="!"&&!this.#t.#c&&this.#w.push(this),this.#S=this.#o?this.#o.#r.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#u!==void 0?this.#u:this.type?this.#u=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#u=this.#r.map(t=>String(t)).join("")}#a(){if(this!==this.#t)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let t;for(;t=this.#w.pop();){if(t.type!=="!")continue;let e=t,s=e.#o;for(;s;){for(let i=e.#S+1;!s.type&&itypeof e=="string"?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#c&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#o?.isStart())return!1;if(this.#S===0)return!0;let t=this.#o;for(let e=0;etypeof f!="string"),l=this.#r.map(f=>{let[m,p,w,g]=typeof f=="string"?n.#E(f,this.#s,a):f.toRegExpSource(t);return this.#s=this.#s||w,this.#n=this.#n||g,m}).join(""),u="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&Ts.has(this.#r[0]))){let m=Cs,p=e&&m.has(l.charAt(0))||l.startsWith("\\.")&&m.has(l.charAt(2))||l.startsWith("\\.\\.")&&m.has(l.charAt(4)),w=!e&&!t&&m.has(l.charAt(0));u=p?vs:w?Ct:""}let c="";return this.isEnd()&&this.#t.#c&&this.#o?.type==="!"&&(c="(?:$|\\/)"),[u+l+c,W(l),this.#s=!!this.#s,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#d(e);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let a=this.toString();return this.#r=[a],this.type=null,this.#s=void 0,[a,W(this.toString()),!1,!1]}let o=!s||t||e||!Ct?"":this.#d(!0);o===r&&(o=""),o&&(r=`(?:${r})(?:${o})*?`);let h="";if(this.type==="!"&&this.#f)h=(this.isStart()&&!e?Ct:"")+Ee;else{let a=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Ct:"")+Se+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;h=i+r+a}return[h,W(r),this.#s=!!this.#s,this.#n]}#d(t){return this.#r.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,i,r,o]=e.toRegExpSource(t);return this.#n=this.#n||o,s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#E(t,e,s=!1){let i=!1,r="",o=!1,h=!1;for(let a=0;ae?t?n.replace(/[?*()[\]{}]/g,"[$&]"):n.replace(/[?*()[\]\\{}]/g,"\\$&"):t?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var O=(n,t,e={})=>(at(t),!e.nocomment&&t.charAt(0)==="#"?!1:new D(t,e).match(n)),Rs=/^\*+([^+@!?\*\[\(]*)$/,Os=n=>t=>!t.startsWith(".")&&t.endsWith(n),Fs=n=>t=>t.endsWith(n),Ds=n=>(n=n.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(n)),Ms=n=>(n=n.toLowerCase(),t=>t.toLowerCase().endsWith(n)),Ns=/^\*+\.\*+$/,_s=n=>!n.startsWith(".")&&n.includes("."),Ls=n=>n!=="."&&n!==".."&&n.includes("."),Ws=/^\.\*+$/,Ps=n=>n!=="."&&n!==".."&&n.startsWith("."),js=/^\*+$/,Is=n=>n.length!==0&&!n.startsWith("."),zs=n=>n.length!==0&&n!=="."&&n!=="..",Bs=/^\?+([^+@!?\*\[\(]*)?$/,Us=([n,t=""])=>{let e=Ce([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},$s=([n,t=""])=>{let e=Te([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Gs=([n,t=""])=>{let e=Te([n]);return t?s=>e(s)&&s.endsWith(t):e},Hs=([n,t=""])=>{let e=Ce([n]);return t?s=>e(s)&&s.endsWith(t):e},Ce=([n])=>{let t=n.length;return e=>e.length===t&&!e.startsWith(".")},Te=([n])=>{let t=n.length;return e=>e.length===t&&e!=="."&&e!==".."},Ae=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",xe={win32:{sep:"\\"},posix:{sep:"/"}},qs=Ae==="win32"?xe.win32.sep:xe.posix.sep;O.sep=qs;var A=Symbol("globstar **");O.GLOBSTAR=A;var Ks="[^/]",Vs=Ks+"*?",Ys="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Xs="(?:(?!(?:\\/|^)\\.).)*?",Js=(n,t={})=>e=>O(e,n,t);O.filter=Js;var N=(n,t={})=>Object.assign({},n,t),Zs=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return O;let t=O;return Object.assign((s,i,r={})=>t(s,i,N(n,r)),{Minimatch:class extends t.Minimatch{constructor(i,r={}){super(i,N(n,r))}static defaults(i){return t.defaults(N(n,i)).Minimatch}},AST:class extends t.AST{constructor(i,r,o={}){super(i,r,N(n,o))}static fromGlob(i,r={}){return t.AST.fromGlob(i,N(n,r))}},unescape:(s,i={})=>t.unescape(s,N(n,i)),escape:(s,i={})=>t.escape(s,N(n,i)),filter:(s,i={})=>t.filter(s,N(n,i)),defaults:s=>t.defaults(N(n,s)),makeRe:(s,i={})=>t.makeRe(s,N(n,i)),braceExpand:(s,i={})=>t.braceExpand(s,N(n,i)),match:(s,i,r={})=>t.match(s,i,N(n,r)),sep:t.sep,GLOBSTAR:A})};O.defaults=Zs;var ke=(n,t={})=>(at(n),t.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:ge(n,{max:t.braceExpandMax}));O.braceExpand=ke;var Qs=(n,t={})=>new D(n,t).makeRe();O.makeRe=Qs;var ti=(n,t,e={})=>{let s=new D(t,e);return n=n.filter(i=>s.match(i)),s.options.nonull&&!n.length&&n.push(t),n};O.match=ti;var ve=/[?*]|[+@!]\(.*?\)|\[|\]/,ei=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),D=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){at(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Ae,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,o,h)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=r[0]===""&&r[1]===""&&(r[2]==="?"||!ve.test(r[2]))&&!ve.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(a)return[...r.slice(0,4),...r.slice(4).map(u=>this.parse(u))];if(l)return[r[0],...r.slice(1).map(u=>this.parse(u))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,i)=>{let r=s[s.length-1];return i==="**"&&r==="**"?s:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(s.pop(),s):(s.push(i),s)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&s.splice(i+1,o-i);let h=s[i+1],a=s[i+2],l=s[i+3];if(h!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(i,1);let u=s.slice(0);u[i]="**",t.push(u),i--}if(!this.preserveMultipleSlashes){for(let o=1;oe.length)}partsMatch(t,e,s=!1){let i=0,r=0,o=[],h="";for(;iE?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:r=1}=this.options;r>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var o=0,h=0,a=t.length,l=e.length;o>> no match, partial?`,t,d,e,f),d===a))}let p;if(typeof u=="string"?(p=c===u,this.debug("string match",u,c,p)):(p=u.test(c),this.debug("pattern match",u,c,p)),!p)return!1}if(o===a&&h===l)return!0;if(o===a)return s;if(h===l)return o===a-1&&t[o]==="";throw new Error("wtf?")}braceExpand(){return ke(this.pattern,this.options)}parse(t){at(t);let e=this.options;if(t==="**")return A;if(t==="")return"";let s,i=null;(s=t.match(js))?i=e.dot?zs:Is:(s=t.match(Rs))?i=(e.nocase?e.dot?Ms:Ds:e.dot?Fs:Os)(s[1]):(s=t.match(Bs))?i=(e.nocase?e.dot?$s:Us:e.dot?Gs:Hs)(s):(s=t.match(Ns))?i=e.dot?Ls:_s:(s=t.match(Ws))&&(i=Ps);let r=Q.fromGlob(t,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,s=e.noglobstar?Vs:e.dot?Ys:Xs,i=new Set(e.nocase?["i"]:[]),r=t.map(a=>{let l=a.map(c=>{if(c instanceof RegExp)for(let d of c.flags.split(""))i.add(d);return typeof c=="string"?ei(c):c===A?A:c._src});l.forEach((c,d)=>{let f=l[d+1],m=l[d-1];c!==A||m===A||(m===void 0?f!==void 0&&f!==A?l[d+1]="(?:\\/|"+s+"\\/)?"+f:l[d]=s:f===void 0?l[d-1]=m+"(?:\\/|\\/"+s+")?":f!==A&&(l[d-1]=m+"(?:\\/|\\/"+s+"\\/)"+f,l[d+1]=A))});let u=l.filter(c=>c!==A);if(this.partial&&u.length>=1){let c=[];for(let d=1;d<=u.length;d++)c.push(u.slice(0,d).join("/"));return"(?:"+c.join("|")+")"}return u.join("/")}).join("|"),[o,h]=t.length>1?["(?:",")"]:["",""];r="^"+o+r+h+"$",this.partial&&(r="^(?:\\/|"+o+r.slice(1,-1)+h+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let s=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let r=this.set;this.debug(this.pattern,"set",r);let o=i[i.length-1];if(!o)for(let h=i.length-2;!o&&h>=0;h--)o=i[h];for(let h=0;h{typeof Vt.emitWarning=="function"?Vt.emitWarning(n,t,e,s):console.error(`[${e}] ${t}: ${n}`)},At=globalThis.AbortController,Re=globalThis.AbortSignal;if(typeof At>"u"){Re=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,s){this._onabort.push(s)}},At=class{constructor(){t()}signal=new Re;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let s of this.signal._onabort)s(e);this.signal.onabort?.(e)}}};let n=Vt.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{n&&(n=!1,Fe("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var ii=n=>!Oe.has(n);var q=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),De=n=>q(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Tt:null:null,Tt=class extends Array{constructor(n){super(n),this.fill(0)}},ri=class ct{heap;length;static#t=!1;static create(t){let e=De(t);if(!e)return[];ct.#t=!0;let s=new ct(t,e);return ct.#t=!1,s}constructor(t,e){if(!ct.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},ft=class Me{#t;#s;#n;#r;#o;#S;#w;#c;get perf(){return this.#c}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#h;#u;#f;#a;#i;#d;#E;#b;#p;#R;#m;#C;#T;#g;#y;#x;#A;#e;#_;static unsafeExposeInternals(t){return{starts:t.#T,ttls:t.#g,autopurgeTimers:t.#y,sizes:t.#C,keyMap:t.#f,keyList:t.#a,valList:t.#i,next:t.#d,prev:t.#E,get head(){return t.#b},get tail(){return t.#p},free:t.#R,isBackgroundFetch:e=>t.#l(e),backgroundFetch:(e,s,i,r)=>t.#U(e,s,i,r),moveToTail:e=>t.#W(e),indexes:e=>t.#F(e),rindexes:e=>t.#D(e),isStale:e=>t.#v(e)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#u}get size(){return this.#h}get fetchMethod(){return this.#S}get memoMethod(){return this.#w}get dispose(){return this.#n}get onInsert(){return this.#r}get disposeAfter(){return this.#o}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:r,updateAgeOnGet:o,updateAgeOnHas:h,allowStale:a,dispose:l,onInsert:u,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:f,maxSize:m=0,maxEntrySize:p=0,sizeCalculation:w,fetchMethod:g,memoMethod:S,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:b,allowStaleOnFetchAbort:z,ignoreFetchAbort:$,perf:J}=t;if(J!==void 0&&typeof J?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#c=J??si,e!==0&&!q(e))throw new TypeError("max option must be a nonnegative integer");let Z=e?De(e):Array;if(!Z)throw new Error("invalid max value: "+e);if(this.#t=e,this.#s=m,this.maxEntrySize=p||this.#s,this.sizeCalculation=w,this.sizeCalculation){if(!this.#s&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=S,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#S=g,this.#A=!!g,this.#f=new Map,this.#a=new Array(e).fill(void 0),this.#i=new Array(e).fill(void 0),this.#d=new Z(e),this.#E=new Z(e),this.#b=0,this.#p=0,this.#R=ri.create(e),this.#h=0,this.#u=0,typeof l=="function"&&(this.#n=l),typeof u=="function"&&(this.#r=u),typeof c=="function"?(this.#o=c,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#x=!!this.#n,this.#_=!!this.#r,this.#e=!!this.#o,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!b,this.allowStaleOnFetchAbort=!!z,this.ignoreFetchAbort=!!$,this.maxEntrySize!==0){if(this.#s!==0&&!q(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!q(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!h,this.ttlResolution=q(i)||i===0?i:1,this.ttlAutopurge=!!r,this.ttl=s||0,this.ttl){if(!q(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#M()}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let $t="LRU_CACHE_UNBOUNDED";ii($t)&&(Oe.add($t),Fe("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",$t,Me))}}getRemainingTTL(t){return this.#f.has(t)?1/0:0}#M(){let t=new Tt(this.#t),e=new Tt(this.#t);this.#g=t,this.#T=e;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#y=s,this.#j=(o,h,a=this.#c.now())=>{if(e[o]=h!==0?a:0,t[o]=h,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),h!==0&&s){let l=setTimeout(()=>{this.#v(o)&&this.#O(this.#a[o],"expire")},h+1);l.unref&&l.unref(),s[o]=l}},this.#k=o=>{e[o]=t[o]!==0?this.#c.now():0},this.#N=(o,h)=>{if(t[h]){let a=t[h],l=e[h];if(!a||!l)return;o.ttl=a,o.start=l,o.now=i||r();let u=o.now-l;o.remainingTTL=a-u}};let i=0,r=()=>{let o=this.#c.now();if(this.ttlResolution>0){i=o;let h=setTimeout(()=>i=0,this.ttlResolution);h.unref&&h.unref()}return o};this.getRemainingTTL=o=>{let h=this.#f.get(o);if(h===void 0)return 0;let a=t[h],l=e[h];if(!a||!l)return 1/0;let u=(i||r())-l;return a-u},this.#v=o=>{let h=e[o],a=t[o];return!!a&&!!h&&(i||r())-h>a}}#k=()=>{};#N=()=>{};#j=()=>{};#v=()=>!1;#G(){let t=new Tt(this.#t);this.#u=0,this.#C=t,this.#P=e=>{this.#u-=t[e],t[e]=0},this.#I=(e,s,i,r)=>{if(this.#l(s))return 0;if(!q(i))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(i=r(s,e),!q(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#L=(e,s,i)=>{if(t[e]=s,this.#s){let r=this.#s-t[e];for(;this.#u>r;)this.#B(!0)}this.#u+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#u)}}#P=t=>{};#L=(t,e,s)=>{};#I=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#F({allowStale:t=this.allowStale}={}){if(this.#h)for(let e=this.#p;!(!this.#z(e)||((t||!this.#v(e))&&(yield e),e===this.#b));)e=this.#E[e]}*#D({allowStale:t=this.allowStale}={}){if(this.#h)for(let e=this.#b;!(!this.#z(e)||((t||!this.#v(e))&&(yield e),e===this.#p));)e=this.#d[e]}#z(t){return t!==void 0&&this.#f.get(this.#a[t])===t}*entries(){for(let t of this.#F())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*rentries(){for(let t of this.#D())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*keys(){for(let t of this.#F()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*rkeys(){for(let t of this.#D()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*values(){for(let t of this.#F())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}*rvalues(){for(let t of this.#D())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#F()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;if(r!==void 0&&t(r,this.#a[s],this))return this.get(this.#a[s],e)}}forEach(t,e=this){for(let s of this.#F()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}rforEach(t,e=this){for(let s of this.#D()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}purgeStale(){let t=!1;for(let e of this.#D({allowStale:!0}))this.#v(e)&&(this.#O(this.#a[e],"expire"),t=!0);return t}info(t){let e=this.#f.get(t);if(e===void 0)return;let s=this.#i[e],i=this.#l(s)?s.__staleWhileFetching:s;if(i===void 0)return;let r={value:i};if(this.#g&&this.#T){let o=this.#g[e],h=this.#T[e];if(o&&h){let a=o-(this.#c.now()-h);r.ttl=a,r.start=Date.now()}}return this.#C&&(r.size=this.#C[e]),r}dump(){let t=[];for(let e of this.#F({allowStale:!0})){let s=this.#a[e],i=this.#i[e],r=this.#l(i)?i.__staleWhileFetching:i;if(r===void 0||s===void 0)continue;let o={value:r};if(this.#g&&this.#T){o.ttl=this.#g[e];let h=this.#c.now()-this.#T[e];o.start=Math.floor(Date.now()-h)}this.#C&&(o.size=this.#C[e]),t.unshift([s,o])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#c.now()-i}this.set(e,s.value,s)}}set(t,e,s={}){if(e===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:r,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:a}=s,{noUpdateTTL:l=this.noUpdateTTL}=s,u=this.#I(t,e,s.size||0,h);if(this.maxEntrySize&&u>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#O(t,"set"),this;let c=this.#h===0?void 0:this.#f.get(t);if(c===void 0)c=this.#h===0?this.#p:this.#R.length!==0?this.#R.pop():this.#h===this.#t?this.#B(!1):this.#h,this.#a[c]=t,this.#i[c]=e,this.#f.set(t,c),this.#d[this.#p]=c,this.#E[c]=this.#p,this.#p=c,this.#h++,this.#L(c,u,a),a&&(a.set="add"),l=!1,this.#_&&this.#r?.(e,t,"add");else{this.#W(c);let d=this.#i[c];if(e!==d){if(this.#A&&this.#l(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=d;f!==void 0&&!o&&(this.#x&&this.#n?.(f,t,"set"),this.#e&&this.#m?.push([f,t,"set"]))}else o||(this.#x&&this.#n?.(d,t,"set"),this.#e&&this.#m?.push([d,t,"set"]));if(this.#P(c),this.#L(c,u,a),this.#i[c]=e,a){a.set="replace";let f=d&&this.#l(d)?d.__staleWhileFetching:d;f!==void 0&&(a.oldValue=f)}}else a&&(a.set="update");this.#_&&this.onInsert?.(e,t,e===d?"update":"replace")}if(i!==0&&!this.#g&&this.#M(),this.#g&&(l||this.#j(c,i,r),a&&this.#N(a,c)),!o&&this.#e&&this.#m){let d=this.#m,f;for(;f=d?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#h;){let t=this.#i[this.#b];if(this.#B(!0),this.#l(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#o?.(...e)}}}#B(t){let e=this.#b,s=this.#a[e],i=this.#i[e];return this.#A&&this.#l(i)?i.__abortController.abort(new Error("evicted")):(this.#x||this.#e)&&(this.#x&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#P(e),this.#y?.[e]&&(clearTimeout(this.#y[e]),this.#y[e]=void 0),t&&(this.#a[e]=void 0,this.#i[e]=void 0,this.#R.push(e)),this.#h===1?(this.#b=this.#p=0,this.#R.length=0):this.#b=this.#d[e],this.#f.delete(s),this.#h--,e}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,r=this.#f.get(t);if(r!==void 0){let o=this.#i[r];if(this.#l(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#v(r))i&&(i.has="stale",this.#N(i,r));else return s&&this.#k(r),i&&(i.has="hit",this.#N(i,r)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{allowStale:s=this.allowStale}=e,i=this.#f.get(t);if(i===void 0||!s&&this.#v(i))return;let r=this.#i[i];return this.#l(r)?r.__staleWhileFetching:r}#U(t,e,s,i){let r=e===void 0?void 0:this.#i[e];if(this.#l(r))return r;let o=new At,{signal:h}=s;h?.addEventListener("abort",()=>o.abort(h.reason),{signal:o.signal});let a={signal:o.signal,options:s,context:i},l=(p,w=!1)=>{let{aborted:g}=o.signal,S=s.ignoreFetchAbort&&p!==void 0,E=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&p!==void 0);if(s.status&&(g&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,S&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),g&&!S&&!w)return c(o.signal.reason,E);let y=f,b=this.#i[e];return(b===f||S&&w&&b===void 0)&&(p===void 0?y.__staleWhileFetching!==void 0?this.#i[e]=y.__staleWhileFetching:this.#O(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,p,a.options))),p},u=p=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=p),c(p,!1)),c=(p,w)=>{let{aborted:g}=o.signal,S=g&&s.allowStaleOnFetchAbort,E=S||s.allowStaleOnFetchRejection,y=E||s.noDeleteOnFetchRejection,b=f;if(this.#i[e]===f&&(!y||!w&&b.__staleWhileFetching===void 0?this.#O(t,"fetch"):S||(this.#i[e]=b.__staleWhileFetching)),E)return s.status&&b.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),b.__staleWhileFetching;if(b.__returned===b)throw p},d=(p,w)=>{let g=this.#S?.(t,r,a);g&&g instanceof Promise&&g.then(S=>p(S===void 0?void 0:S),w),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(p(void 0),s.allowStaleOnFetchAbort&&(p=S=>l(S,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(d).then(l,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:r,__returned:void 0});return e===void 0?(this.set(t,m,{...a.options,status:void 0}),e=this.#f.get(t)):this.#i[e]=m,m}#l(t){if(!this.#A)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof At}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:w=!1,status:g,signal:S}=e;if(!this.#A)return g&&(g.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,status:g});let E={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,ttl:o,noDisposeOnSet:h,size:a,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:g,signal:S},y=this.#f.get(t);if(y===void 0){g&&(g.fetch="miss");let b=this.#U(t,y,E,p);return b.__returned=b}else{let b=this.#i[y];if(this.#l(b)){let Z=s&&b.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",Z&&(g.returnedStale=!0)),Z?b.__staleWhileFetching:b.__returned=b}let z=this.#v(y);if(!w&&!z)return g&&(g.fetch="hit"),this.#W(y),i&&this.#k(y),g&&this.#N(g,y),b;let $=this.#U(t,y,E,p),J=$.__staleWhileFetching!==void 0&&s;return g&&(g.fetch=z?"stale":"refresh",J&&z&&(g.returnedStale=!0)),J?$.__staleWhileFetching:$.__returned=$}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:r,...o}=e,h=this.get(t,o);if(!r&&h!==void 0)return h;let a=s(t,h,{options:o,context:i});return this.set(t,a,o),a}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:o}=e,h=this.#f.get(t);if(h!==void 0){let a=this.#i[h],l=this.#l(a);return o&&this.#N(o,h),this.#v(h)?(o&&(o.get="stale"),l?(o&&s&&a.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?a.__staleWhileFetching:void 0):(r||this.#O(t,"expire"),o&&s&&(o.returnedStale=!0),s?a:void 0)):(o&&(o.get="hit"),l?a.__staleWhileFetching:(this.#W(h),i&&this.#k(h),a))}else o&&(o.get="miss")}#$(t,e){this.#E[e]=t,this.#d[t]=e}#W(t){t!==this.#p&&(t===this.#b?this.#b=this.#d[t]:this.#$(this.#E[t],this.#d[t]),this.#$(this.#p,t),this.#p=t)}delete(t){return this.#O(t,"delete")}#O(t,e){let s=!1;if(this.#h!==0){let i=this.#f.get(t);if(i!==void 0)if(this.#y?.[i]&&(clearTimeout(this.#y?.[i]),this.#y[i]=void 0),s=!0,this.#h===1)this.#H(e);else{this.#P(i);let r=this.#i[i];if(this.#l(r)?r.__abortController.abort(new Error("deleted")):(this.#x||this.#e)&&(this.#x&&this.#n?.(r,t,e),this.#e&&this.#m?.push([r,t,e])),this.#f.delete(t),this.#a[i]=void 0,this.#i[i]=void 0,i===this.#p)this.#p=this.#E[i];else if(i===this.#b)this.#b=this.#d[i];else{let o=this.#E[i];this.#d[o]=this.#d[i];let h=this.#d[i];this.#E[h]=this.#E[i]}this.#h--,this.#R.push(i)}}if(this.#e&&this.#m?.length){let i=this.#m,r;for(;r=i?.shift();)this.#o?.(...r)}return s}clear(){return this.#H("delete")}#H(t){for(let e of this.#D({allowStale:!0})){let s=this.#i[e];if(this.#l(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#a[e];this.#x&&this.#n?.(s,i,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#f.clear(),this.#i.fill(void 0),this.#a.fill(void 0),this.#g&&this.#T){this.#g.fill(0),this.#T.fill(0);for(let e of this.#y??[])e!==void 0&&clearTimeout(e);this.#y?.fill(void 0)}if(this.#C&&this.#C.fill(0),this.#b=0,this.#p=0,this.#R.length=0,this.#u=0,this.#h=0,this.#e&&this.#m){let e=this.#m,s;for(;s=e?.shift();)this.#o?.(...s)}}};import{posix as mi,win32 as re}from"node:path";import{fileURLToPath as gi}from"node:url";import{lstatSync as wi,readdir as yi,readdirSync as bi,readlinkSync as Si,realpathSync as Ei}from"fs";import*as xi from"node:fs";import{lstat as Ci,readdir as Ti,readlink as Ai,realpath as ki}from"node:fs/promises";import{EventEmitter as ee}from"node:events";import Pe from"node:stream";import{StringDecoder as ni}from"node:string_decoder";var Ne=typeof process=="object"&&process?process:{stdout:null,stderr:null},oi=n=>!!n&&typeof n=="object"&&(n instanceof V||n instanceof Pe||hi(n)||ai(n)),hi=n=>!!n&&typeof n=="object"&&n instanceof ee&&typeof n.pipe=="function"&&n.pipe!==Pe.Writable.prototype.pipe,ai=n=>!!n&&typeof n=="object"&&n instanceof ee&&typeof n.write=="function"&&typeof n.end=="function",G=Symbol("EOF"),H=Symbol("maybeEmitEnd"),K=Symbol("emittedEnd"),kt=Symbol("emittingEnd"),ut=Symbol("emittedError"),Rt=Symbol("closed"),_e=Symbol("read"),Ot=Symbol("flush"),Le=Symbol("flushChunk"),P=Symbol("encoding"),et=Symbol("decoder"),v=Symbol("flowing"),dt=Symbol("paused"),st=Symbol("resume"),C=Symbol("buffer"),F=Symbol("pipes"),T=Symbol("bufferLength"),Yt=Symbol("bufferPush"),Ft=Symbol("bufferShift"),k=Symbol("objectMode"),x=Symbol("destroyed"),Xt=Symbol("error"),Jt=Symbol("emitData"),We=Symbol("emitEnd"),Zt=Symbol("emitEnd2"),B=Symbol("async"),Qt=Symbol("abort"),Dt=Symbol("aborted"),pt=Symbol("signal"),Y=Symbol("dataListeners"),M=Symbol("discarded"),mt=n=>Promise.resolve().then(n),li=n=>n(),ci=n=>n==="end"||n==="finish"||n==="prefinish",fi=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,ui=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),Mt=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[st](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},te=class extends Mt{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},di=n=>!!n.objectMode,pi=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",V=class extends ee{[v]=!1;[dt]=!1;[F]=[];[C]=[];[k];[P];[B];[et];[G]=!1;[K]=!1;[kt]=!1;[Rt]=!1;[ut]=null;[T]=0;[x]=!1;[pt];[Dt]=!1;[Y]=0;[M]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");di(e)?(this[k]=!0,this[P]=null):pi(e)?(this[P]=e.encoding,this[k]=!1):(this[k]=!1,this[P]=null),this[B]=!!e.async,this[et]=this[P]?new ni(this[P]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[F]});let{signal:s}=e;s&&(this[pt]=s,s.aborted?this[Qt]():s.addEventListener("abort",()=>this[Qt]()))}get bufferLength(){return this[T]}get encoding(){return this[P]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[k]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[B]}set async(t){this[B]=this[B]||!!t}[Qt](){this[Dt]=!0,this.emit("abort",this[pt]?.reason),this.destroy(this[pt]?.reason)}get aborted(){return this[Dt]}set aborted(t){}write(t,e,s){if(this[Dt])return!1;if(this[G])throw new Error("write after end");if(this[x])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[B]?mt:li;if(!this[k]&&!Buffer.isBuffer(t)){if(ui(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(fi(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[k]?(this[v]&&this[T]!==0&&this[Ot](!0),this[v]?this.emit("data",t):this[Yt](t),this[T]!==0&&this.emit("readable"),s&&i(s),this[v]):t.length?(typeof t=="string"&&!(e===this[P]&&!this[et]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[P]&&(t=this[et].write(t)),this[v]&&this[T]!==0&&this[Ot](!0),this[v]?this.emit("data",t):this[Yt](t),this[T]!==0&&this.emit("readable"),s&&i(s),this[v]):(this[T]!==0&&this.emit("readable"),s&&i(s),this[v])}read(t){if(this[x])return null;if(this[M]=!1,this[T]===0||t===0||t&&t>this[T])return this[H](),null;this[k]&&(t=null),this[C].length>1&&!this[k]&&(this[C]=[this[P]?this[C].join(""):Buffer.concat(this[C],this[T])]);let e=this[_e](t||null,this[C][0]);return this[H](),e}[_e](t,e){if(this[k])this[Ft]();else{let s=e;t===s.length||t===null?this[Ft]():typeof s=="string"?(this[C][0]=s.slice(t),e=s.slice(0,t),this[T]-=t):(this[C][0]=s.subarray(t),e=s.subarray(0,t),this[T]-=t)}return this.emit("data",e),!this[C].length&&!this[G]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[G]=!0,this.writable=!1,(this[v]||!this[dt])&&this[H](),this}[st](){this[x]||(!this[Y]&&!this[F].length&&(this[M]=!0),this[dt]=!1,this[v]=!0,this.emit("resume"),this[C].length?this[Ot]():this[G]?this[H]():this.emit("drain"))}resume(){return this[st]()}pause(){this[v]=!1,this[dt]=!0,this[M]=!1}get destroyed(){return this[x]}get flowing(){return this[v]}get paused(){return this[dt]}[Yt](t){this[k]?this[T]+=1:this[T]+=t.length,this[C].push(t)}[Ft](){return this[k]?this[T]-=1:this[T]-=this[C][0].length,this[C].shift()}[Ot](t=!1){do;while(this[Le](this[Ft]())&&this[C].length);!t&&!this[C].length&&!this[G]&&this.emit("drain")}[Le](t){return this.emit("data",t),this[v]}pipe(t,e){if(this[x])return t;this[M]=!1;let s=this[K];return e=e||{},t===Ne.stdout||t===Ne.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[F].push(e.proxyErrors?new te(this,t,e):new Mt(this,t,e)),this[B]?mt(()=>this[st]()):this[st]()),t}unpipe(t){let e=this[F].find(s=>s.dest===t);e&&(this[F].length===1?(this[v]&&this[Y]===0&&(this[v]=!1),this[F]=[]):this[F].splice(this[F].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[M]=!1,this[Y]++,!this[F].length&&!this[v]&&this[st]();else if(t==="readable"&&this[T]!==0)super.emit("readable");else if(ci(t)&&this[K])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ut]){let i=e;this[B]?mt(()=>i.call(this,this[ut])):i.call(this,this[ut])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Y]=this.listeners("data").length,this[Y]===0&&!this[M]&&!this[F].length&&(this[v]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Y]=0,!this[M]&&!this[F].length&&(this[v]=!1)),e}get emittedEnd(){return this[K]}[H](){!this[kt]&&!this[K]&&!this[x]&&this[C].length===0&&this[G]&&(this[kt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Rt]&&this.emit("close"),this[kt]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==x&&this[x])return!1;if(t==="data")return!this[k]&&!s?!1:this[B]?(mt(()=>this[Jt](s)),!0):this[Jt](s);if(t==="end")return this[We]();if(t==="close"){if(this[Rt]=!0,!this[K]&&!this[x])return!1;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(t==="error"){this[ut]=s,super.emit(Xt,s);let r=!this[pt]||this.listeners("error").length?super.emit("error",s):!1;return this[H](),r}else if(t==="resume"){let r=super.emit("resume");return this[H](),r}else if(t==="finish"||t==="prefinish"){let r=super.emit(t);return this.removeAllListeners(t),r}let i=super.emit(t,...e);return this[H](),i}[Jt](t){for(let s of this[F])s.dest.write(t)===!1&&this.pause();let e=this[M]?!1:super.emit("data",t);return this[H](),e}[We](){return this[K]?!1:(this[K]=!0,this.readable=!1,this[B]?(mt(()=>this[Zt]()),!0):this[Zt]())}[Zt](){if(this[et]){let e=this[et].end();if(e){for(let s of this[F])s.dest.write(e);this[M]||super.emit("data",e)}}for(let e of this[F])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[k]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[k]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[k])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[P]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(x,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[M]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[G])return e();let r,o,h=c=>{this.off("data",a),this.off("end",l),this.off(x,u),e(),o(c)},a=c=>{this.off("error",h),this.off("end",l),this.off(x,u),this.pause(),r({value:c,done:!!this[G]})},l=()=>{this.off("error",h),this.off("data",a),this.off(x,u),e(),r({done:!0,value:void 0})},u=()=>h(new Error("stream destroyed"));return new Promise((c,d)=>{o=d,r=c,this.once(x,u),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[M]=!1;let t=!1,e=()=>(this.pause(),this.off(Xt,e),this.off(x,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Xt,e),this.once(x,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[x])return t?this.emit("error",t):this.emit(x),this;this[x]=!0,this[M]=!0,this[C].length=0,this[T]=0;let e=this;return typeof e.close=="function"&&!this[Rt]&&e.close(),t?this.emit("error",t):this.emit(x),this}static get isStream(){return oi}};var vi=Ei.native,wt={lstatSync:wi,readdir:yi,readdirSync:bi,readlinkSync:Si,realpathSync:vi,promises:{lstat:Ci,readdir:Ti,readlink:Ai,realpath:ki}},Ue=n=>!n||n===wt||n===xi?wt:{...wt,...n,promises:{...wt.promises,...n.promises||{}}},$e=/^\\\\\?\\([a-z]:)\\?$/i,Ri=n=>n.replace(/\//g,"\\").replace($e,"$1\\"),Oi=/[\\\/]/,L=0,Ge=1,He=2,U=4,qe=6,Ke=8,X=10,Ve=12,_=15,gt=~_,se=16,je=32,yt=64,j=128,Nt=256,Lt=512,Ie=yt|j|Lt,Fi=1023,ie=n=>n.isFile()?Ke:n.isDirectory()?U:n.isSymbolicLink()?X:n.isCharacterDevice()?He:n.isBlockDevice()?qe:n.isSocket()?Ve:n.isFIFO()?Ge:L,ze=new ft({max:2**12}),bt=n=>{let t=ze.get(n);if(t)return t;let e=n.normalize("NFKD");return ze.set(n,e),e},Be=new ft({max:2**12}),_t=n=>{let t=Be.get(n);if(t)return t;let e=bt(n.toLowerCase());return Be.set(n,e),e},Wt=class extends ft{constructor(){super({max:256})}},ne=class extends ft{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},Ye=Symbol("PathScurry setAsCwd"),R=class{name;root;roots;parent;nocase;isCWD=!1;#t;#s;get dev(){return this.#s}#n;get mode(){return this.#n}#r;get nlink(){return this.#r}#o;get uid(){return this.#o}#S;get gid(){return this.#S}#w;get rdev(){return this.#w}#c;get blksize(){return this.#c}#h;get ino(){return this.#h}#u;get size(){return this.#u}#f;get blocks(){return this.#f}#a;get atimeMs(){return this.#a}#i;get mtimeMs(){return this.#i}#d;get ctimeMs(){return this.#d}#E;get birthtimeMs(){return this.#E}#b;get atime(){return this.#b}#p;get mtime(){return this.#p}#R;get ctime(){return this.#R}#m;get birthtime(){return this.#m}#C;#T;#g;#y;#x;#A;#e;#_;#M;#k;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=L,s,i,r,o,h){this.name=t,this.#C=r?_t(t):bt(t),this.#e=e&Fi,this.nocase=r,this.roots=i,this.root=s||this,this.#_=o,this.#g=h.fullpath,this.#x=h.relative,this.#A=h.relativePosix,this.parent=h.parent,this.parent?this.#t=this.parent.#t:this.#t=Ue(h.fs)}depth(){return this.#T!==void 0?this.#T:this.parent?this.#T=this.parent.depth()+1:this.#T=0}childrenCache(){return this.#_}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#N(i):this.#N(i)}#N(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#_.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#_.set(this,e),this.#e&=~se,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?_t(t):bt(t);for(let a of s)if(a.#C===i)return a;let r=this.parent?this.sep:"",o=this.#g?this.#g+r+t:void 0,h=this.newChild(t,L,{...e,parent:this,fullpath:o});return this.canReaddir()||(h.#e|=j),s.push(h),h}relative(){if(this.isCWD)return"";if(this.#x!==void 0)return this.#x;let t=this.name,e=this.parent;if(!e)return this.#x=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#A!==void 0)return this.#A;let t=this.name,e=this.parent;if(!e)return this.#A=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=i}fullpathPosix(){if(this.#y!==void 0)return this.#y;if(this.sep==="/")return this.#y=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#y=`//?/${i}`:this.#y=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#y=s}isUnknown(){return(this.#e&_)===L}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&_)===Ke}isDirectory(){return(this.#e&_)===U}isCharacterDevice(){return(this.#e&_)===He}isBlockDevice(){return(this.#e&_)===qe}isFIFO(){return(this.#e&_)===Ge}isSocket(){return(this.#e&_)===Ve}isSymbolicLink(){return(this.#e&X)===X}lstatCached(){return this.#e&je?this:void 0}readlinkCached(){return this.#M}realpathCached(){return this.#k}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#M)return!0;if(!this.parent)return!1;let t=this.#e&_;return!(t!==L&&t!==X||this.#e&Nt||this.#e&j)}calledReaddir(){return!!(this.#e&se)}isENOENT(){return!!(this.#e&j)}isNamed(t){return this.nocase?this.#C===_t(t):this.#C===bt(t)}async readlink(){let t=this.#M;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#M=s}catch(e){this.#D(e.code);return}}readlinkSync(){let t=this.#M;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#M=s}catch(e){this.#D(e.code);return}}#j(t){this.#e|=se;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let r=s.slice(0,s.provisional);e?t(null,r):queueMicrotask(()=>t(null,r));return}if(this.#W.push(t),this.#O)return;this.#O=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(r,o)=>{if(r)this.#I(r.code),s.provisional=0;else{for(let h of o)this.#z(h,s);this.#j(s)}this.#H(s.slice(0,s.provisional))})}#q;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#q)await this.#q;else{let s=()=>{};this.#q=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#z(i,t);this.#j(t)}catch(i){this.#I(i.code),t.provisional=0}this.#q=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#z(s,t);this.#j(t)}catch(s){this.#I(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&Ie)return!1;let t=_&this.#e;return t===L||t===U||t===X}shouldWalk(t,e){return(this.#e&U)===U&&!(this.#e&Ie)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#k)return this.#k;if(!((Lt|Nt|j)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#k=this.resolve(t)}catch{this.#P()}}realpathSync(){if(this.#k)return this.#k;if(!((Lt|Nt|j)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#k=this.resolve(t)}catch{this.#P()}}[Ye](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#x=s.join(this.sep),i.#A=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#x=void 0,i.#A=void 0,i=i.parent}},Pt=class n extends R{sep="\\";splitSep=Oi;constructor(t,e=L,s,i,r,o,h){super(t,e,s,i,r,o,h)}newChild(t,e=L,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return re.parse(t).root}getRoot(t){if(t=Ri(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new it(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace($e,"$1\\"),t===e}},jt=class n extends R{splitSep="/";sep="/";constructor(t,e=L,s,i,r,o,h){super(t,e,s,i,r,o,h)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=L,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}},It=class{root;rootPath;roots;cwd;#t;#s;#n;nocase;#r;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:r=16*1024,fs:o=wt}={}){this.#r=Ue(o),(t instanceof URL||t.startsWith("file://"))&&(t=gi(t));let h=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(h),this.#t=new Wt,this.#s=new Wt,this.#n=new ne(r);let a=h.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1,c=e.sep,d=this.rootPath,f=!1;for(let m of a){let p=u--;l=l.child(m,{relative:new Array(p).fill("..").join(c),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(f?"":c)+m}),f=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let r=t.length-1;r>=0;r--){let o=t[r];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let r=t.length-1;r>=0;r--){let o=t[r];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#s.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(r=>r.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e,h=[];(!r||r(t))&&h.push(s?t:t.fullpath());let a=new Set,l=(c,d)=>{a.add(c),c.readdirCB((f,m)=>{if(f)return d(f);let p=m.length;if(!p)return d();let w=()=>{--p===0&&d()};for(let g of m)(!r||r(g))&&h.push(s?g:g.fullpath()),i&&g.isSymbolicLink()?g.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,o)?l(S,w):w()):g.shouldWalk(a,o)?l(g,w):w()},!0)},u=t;return new Promise((c,d)=>{l(u,f=>{if(f)return d(f);c(h)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e,h=[];(!r||r(t))&&h.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let u=l.readdirSync();for(let c of u){(!r||r(c))&&h.push(s?c:c.fullpath());let d=c;if(c.isSymbolicLink()){if(!(i&&(d=c.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,o)&&a.add(d)}}return h}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e;(!r||r(t))&&(yield s?t:t.fullpath());let h=new Set([t]);for(let a of h){let l=a.readdirSync();for(let u of l){(!r||r(u))&&(yield s?u:u.fullpath());let c=u;if(u.isSymbolicLink()){if(!(i&&(c=u.realpathSync())))continue;c.isUnknown()&&c.lstatSync()}c.shouldWalk(h,o)&&h.add(c)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e,h=new V({objectMode:!0});(!r||r(t))&&h.write(s?t:t.fullpath());let a=new Set,l=[t],u=0,c=()=>{let d=!1;for(;!d;){let f=l.shift();if(!f){u===0&&h.end();return}u++,a.add(f);let m=(w,g,S=!1)=>{if(w)return h.emit("error",w);if(i&&!S){let E=[];for(let y of g)y.isSymbolicLink()&&E.push(y.realpath().then(b=>b?.isUnknown()?b.lstat():b));if(E.length){Promise.all(E).then(()=>m(null,g,!0));return}}for(let E of g)E&&(!r||r(E))&&(h.write(s?E:E.fullpath())||(d=!0));u--;for(let E of g){let y=E.realpathCached()||E;y.shouldWalk(a,o)&&l.push(y)}d&&!h.flowing?h.once("drain",c):p||c()},p=!0;f.readdirCB(m,!0),p=!1}};return c(),h}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof R||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:o}=e,h=new V({objectMode:!0}),a=new Set;(!r||r(t))&&h.write(s?t:t.fullpath());let l=[t],u=0,c=()=>{let d=!1;for(;!d;){let f=l.shift();if(!f){u===0&&h.end();return}u++,a.add(f);let m=f.readdirSync();for(let p of m)(!r||r(p))&&(h.write(s?p:p.fullpath())||(d=!0));u--;for(let p of m){let w=p;if(p.isSymbolicLink()){if(!(i&&(w=p.realpathSync())))continue;w.isUnknown()&&w.lstatSync()}w.shouldWalk(a,o)&&l.push(w)}}d&&!h.flowing&&h.once("drain",c)};return c(),h}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[Ye](e)}},it=class extends It{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,re,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return re.parse(t).root.toUpperCase()}newRoot(t){return new Pt(this.rootPath,U,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},rt=class extends It{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,mi,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new jt(this.rootPath,U,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},St=class extends rt{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}},Cr=process.platform==="win32"?Pt:jt,Xe=process.platform==="win32"?it:process.platform==="darwin"?St:rt;var Di=n=>n.length>=1,Mi=n=>n.length>=1,Ni=Symbol.for("nodejs.util.inspect.custom"),nt=class n{#t;#s;#n;length;#r;#o;#S;#w;#c;#h;#u=!0;constructor(t,e,s,i){if(!Di(t))throw new TypeError("empty pattern list");if(!Mi(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#s=e,this.#n=s,this.#r=i,this.#n===0){if(this.isUNC()){let[r,o,h,a,...l]=this.#t,[u,c,d,f,...m]=this.#s;l[0]===""&&(l.shift(),m.shift());let p=[r,o,h,a,""].join("/"),w=[u,c,d,f,""].join("/");this.#t=[p,...l],this.#s=[w,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[r,...o]=this.#t,[h,...a]=this.#s;o[0]===""&&(o.shift(),a.shift());let l=r+"/",u=h+"/";this.#t=[l,...o],this.#s=[u,...a],this.length=this.#t.length}}}[Ni](){return"Pattern <"+this.#s.slice(this.#n).join("/")+">"}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===A}isRegExp(){return this.#t[this.#n]instanceof RegExp}globString(){return this.#S=this.#S||(this.#n===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new n(this.#t,this.#s,this.#n+1,this.#r),this.#o.#h=this.#h,this.#o.#c=this.#c,this.#o.#w=this.#w,this.#o):this.#o=null}isUNC(){let t=this.#t;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#w!==void 0?this.#w:this.#w=this.#r==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#u)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#u?!1:(this.#u=!1,!0)}};var _i=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ot=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:r,platform:o=_i}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:r,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(let h of t)this.add(h)}add(t){let e=new D(t,this.mmopts);for(let s=0;s[t,!!(e&2),!!(e&1)])}},ae=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},Et=class n{hasWalkedCache;matches=new he;subwalks=new ae;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new oe}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,r]of s){this.hasWalkedCache.storeWalked(i,r);let o=r.root(),h=r.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let c=r.rest();if(c)r=c;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let a,l,u=!1;for(;typeof(a=r.pattern())=="string"&&(l=r.rest());)i=i.resolve(a),r=l,u=!0;if(a=r.pattern(),l=r.rest(),u){if(this.hasWalkedCache.hasWalked(i,r))continue;this.hasWalkedCache.storeWalked(i,r)}if(typeof a=="string"){let c=a===".."||a===""||a===".";this.matches.add(i.resolve(a),h,c);continue}else if(a===A){(!i.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(i,r);let c=l?.pattern(),d=l?.rest();if(!l||(c===""||c===".")&&!d)this.matches.add(i,h,c===""||c===".");else if(c===".."){let f=i.parent||i;d?this.hasWalkedCache.hasWalked(f,d)||this.subwalks.add(f,d):this.matches.add(f,h,!0)}}else a instanceof RegExp&&this.subwalks.add(i,r)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let r of e)for(let o of s){let h=o.isAbsolute(),a=o.pattern(),l=o.rest();a===A?i.testGlobstar(r,o,l,h):a instanceof RegExp?i.testRegExp(r,a,l,h):i.testString(r,a,l,h)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let r=s.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(t,r,s.rest(),i);else if(r===".."){let o=t.parent||t;this.subwalks.add(o,s)}else r instanceof RegExp&&this.testRegExp(t,r,s.rest(),i)}}testRegExp(t,e,s,i){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};var Li=(n,t)=>typeof n=="string"?new ot([n],t):Array.isArray(n)?new ot(n,t):n,zt=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#n;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#n=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#s=Li(s.ignore??[],s),!this.includeChildMatches&&typeof this.#s.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#r(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#o(t){return!!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let o=await r.realpath();o&&(o.isUnknown()||this.opts.stat)&&await o.lstat()}return this.matchCheckTest(r,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#r(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let o=r.realpathSync();o&&(o?.isUnknown()||this.opts.stat)&&o.lstatSync()}return this.matchCheckTest(r,e)}matchFinish(t,e){if(this.#r(t))return;if(!this.includeChildMatches&&this.#s?.add){let r=`${t.relativePosix()}/**`;this.#s.add(r)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let r=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(r+i)}else{let r=this.opts.posix?t.relativePosix():t.relative(),o=this.opts.dotRelative&&!r.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(r?o+r+i:"."+i)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.matchFinish(i,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Et(this.opts),s)}walkCB2(t,e,s,i){if(this.#o(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let r=1,o=()=>{--r===0&&i()};for(let[h,a,l]of s.matches.entries())this.#r(h)||(r++,this.match(h,a,l).then(()=>o()));for(let h of s.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;r++;let a=h.readdirCached();h.calledReaddir()?this.walkCB3(h,a,s,o):h.readdirCB((l,u)=>this.walkCB3(h,u,s,o),!0)}o()}walkCB3(t,e,s,i){s=s.filterEntries(t,e);let r=1,o=()=>{--r===0&&i()};for(let[h,a,l]of s.matches.entries())this.#r(h)||(r++,this.match(h,a,l).then(()=>o()));for(let[h,a]of s.subwalks.entries())r++,this.walkCB2(h,a,s.child(),o);o()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Et(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#o(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let r=1,o=()=>{--r===0&&i()};for(let[h,a,l]of s.matches.entries())this.#r(h)||this.matchSync(h,a,l);for(let h of s.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;r++;let a=h.readdirSync();this.walkCB3Sync(h,a,s,o)}o()}walkCB3Sync(t,e,s,i){s=s.filterEntries(t,e);let r=1,o=()=>{--r===0&&i()};for(let[h,a,l]of s.matches.entries())this.#r(h)||this.matchSync(h,a,l);for(let[h,a]of s.subwalks.entries())r++,this.walkCB2Sync(h,a,s.child(),o);o()}},xt=class extends zt{matches=new Set;constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},vt=class extends zt{results;constructor(t,e,s){super(t,e,s),this.results=new V({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var Pi=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",I=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=Wi(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||Pi,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?it:e.platform==="darwin"?St:e.platform?rt:Xe;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",i={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(a=>new D(a,i)),[o,h]=r.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=o.map((a,l)=>{let u=h[l];if(!u)throw new Error("invalid pattern object");return new nt(a,u,0,this.platform)})}async walk(){return[...await new xt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new xt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new vt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new vt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var le=(n,t={})=>{Array.isArray(n)||(n=[n]);for(let e of n)if(new D(e,t).hasMagic())return!0;return!1};function Bt(n,t={}){return new I(n,t).streamSync()}function Qe(n,t={}){return new I(n,t).stream()}function ts(n,t={}){return new I(n,t).walkSync()}async function Je(n,t={}){return new I(n,t).walk()}function Ut(n,t={}){return new I(n,t).iterateSync()}function es(n,t={}){return new I(n,t).iterate()}var ji=Bt,Ii=Object.assign(Qe,{sync:Bt}),zi=Ut,Bi=Object.assign(es,{sync:Ut}),Ui=Object.assign(ts,{stream:Bt,iterate:Ut}),Ze=Object.assign(Je,{glob:Je,globSync:ts,sync:Ui,globStream:Qe,stream:Ii,globStreamSync:Bt,streamSync:ji,globIterate:es,iterate:Bi,globIterateSync:Ut,iterateSync:zi,Glob:I,hasMagic:le,escape:tt,unescape:W});Ze.glob=Ze;export{I as Glob,ot as Ignore,tt as escape,Ze as glob,es as globIterate,Ut as globIterateSync,Qe as globStream,Bt as globStreamSync,ts as globSync,le as hasMagic,Bi as iterate,zi as iterateSync,Ii as stream,ji as streamSync,Ui as sync,W as unescape};
+var re=(r,t,e)=>{let s=r instanceof RegExp?We(r,e):r,i=t instanceof RegExp?We(t,e):t,n=s!==null&&i!=null&&js(s,i,e);return n&&{start:n[0],end:n[1],pre:e.slice(0,n[0]),body:e.slice(n[0]+s.length,n[1]),post:e.slice(n[1]+i.length)}},We=(r,t)=>{let e=t.match(r);return e?e[0]:null},js=(r,t,e)=>{let s,i,n,o,h,a=e.indexOf(r),l=e.indexOf(t,a+1),c=a;if(a>=0&&l>0){if(r===t)return[a,l];for(s=[],n=e.length;c>=0&&!h;){if(c===a)s.push(c),a=e.indexOf(r,c+1);else if(s.length===1){let f=s.pop();f!==void 0&&(h=[f,l])}else i=s.pop(),i!==void 0&&i=0?a:l}s.length&&o!==void 0&&(h=[n,o])}return h};var $e="\0SLASH"+Math.random()+"\0",Ie="\0OPEN"+Math.random()+"\0",le="\0CLOSE"+Math.random()+"\0",Be="\0COMMA"+Math.random()+"\0",Ue="\0PERIOD"+Math.random()+"\0",Ws=new RegExp($e,"g"),$s=new RegExp(Ie,"g"),Is=new RegExp(le,"g"),Bs=new RegExp(Be,"g"),Us=new RegExp(Ue,"g"),Gs=/\\\\/g,Hs=/\\{/g,qs=/\\}/g,Ks=/\\,/g,Xs=/\\\./g,Vs=1e5,Ys=4e6,Js=1e3,Zs=1e3;function oe(r){return isNaN(r)?r.charCodeAt(0):parseInt(r,10)}function Qs(r){return r.replace(Gs,$e).replace(Hs,Ie).replace(qs,le).replace(Ks,Be).replace(Xs,Ue)}function ti(r){return r.replace(Ws,"\\").replace($s,"{").replace(Is,"}").replace(Bs,",").replace(Us,".")}function he(r,t){for(let e=0;e=t}function ct(r,t,e,s,i,n){let o=[],h=0;for(let a=0;a=s)return o;let c=r[a]+t+e[l];if(!(n&&!c)){if(h+c.length>i)return o;o.push(c),h+=c.length}}return o}function oi(r,t,e,s){let i=r.split(/\.\./),n=[];if(i[0]===void 0||i[1]===void 0)return n;let o=oe(i[0]),h=oe(i[1]),a=Math.max(i[0].length,i[1].length),l=i.length===3&&i[2]!==void 0?Math.max(Math.abs(oe(i[2])),1):1,c=ni;h0){let m=new Array(w+1).join("0");g<0?d="-"+m+d.slice(1):d=m+d}}if(p+d.length>s)break;n.push(d),p+=d.length}return n}function ae(r,t,e,s,i,n,o){if(i>s)return[r];let h=[""],a=0,l=!1,c=!0;for(;;){let f=re("{","}",r);if(!f)return ct(h,r,[""],t,e,l);let u=f.pre;if(/\$$/.test(u)){if(h=ct(h,u+"{"+f.body+"}",[""],t,e,l&&!f.post.length),c=!1,!f.post.length)break;r=f.post;continue}let p=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(f.body),g=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(f.body),d=p||g,w=f.body.indexOf(",")>=0;if(!d&&!w){if(a=t||S+B.length>e)break t;m.push(B),S+=B.length}}}}if(h=ct(h,u,m,t,e,l&&!f.post.length),!f.post.length)break;r=f.post}return h}var fe=(r,t)=>r===t?{t:"lit",ch:String(r)}:{t:"class",re:new RegExp(`^[${r}-${t}]$`)},ce=(r,t)=>t.map(e=>[fe(r,r),...e]),ft=(r,t)=>{if(!r)return[[]];let e=+r[0],s=+t[0],i=r.slice(1),n=t.slice(1);if(e===s)return ce(e,ft(i,n));let o="0".repeat(i.length),h="9".repeat(i.length),a=[];i!==o&&a.push(...ce(e++,ft(i,h)));let l=n===h?[]:ce(s--,ft(o,n));return e<=s&&a.push([fe(e,s),...Array.from(i,()=>fe(0,9))]),a.push(...l),a},He=(r,t,e)=>{if(e)return ft(String(r).padStart(e,"0"),String(t).padStart(e,"0"));let s=[];for(let i=String(r).length;i<=String(t).length;i++){let n=Math.max(r,i===1?0:10**(i-1)),o=Math.min(t,10**i-1);s.push(...ft(String(n),String(o)))}return s},qe=(r,t)=>{let e=Number(r),s=Number(t);if(!Number.isSafeInteger(e)||!Number.isSafeInteger(s))return;e>s&&([e,s]=[s,e]);let n=/^-?0\d/.test(r)||/^-?0\d/.test(t)?Math.max(r.length,t.length):0,o=[];if(e<0){let h=He(Math.max(-s,1),-e,n&&n-1);o.push(...h.map(a=>[{t:"lit",ch:"-"},...a]))}return s>=0&&o.push(...He(Math.max(e,0),s,n)),o};var hi={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},ut=r=>r.replace(/[[\]\\-]/g,"\\$&"),ue=/$./,Ke=(r,t,e=!1,s)=>{let i=m=>{let b=s?m.normalize(s):m;return[...b].length===1?b:m},n=t;if(r.charAt(n)!=="[")throw new Error("not in a brace expression");let o=[],h=[],a=n+1,l=!1,c=!1,f=!1,u=n,p="";t:for(;ap.codePointAt(0)?o.push(ut(p)+"-"+ut(b)):b===p&&o.push(ut(b)),p="",a+=m.length;continue}if(r.startsWith("-]",a+m.length)){o.push(ut(b+"-")),a+=m.length+1;continue}if(r.startsWith("-",a+m.length)){p=b,a+=m.length+1;continue}o.push(ut(b)),a+=m.length}if(u({t:"lit",ch:r}),li=r=>r.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),Je=r=>new RegExp(`^${li(r)}$`,"iu"),Dt=new Map,Ze=r=>{let t=Dt.get(r);return t||(t=Je(r),Dt.size>=1e3&&Dt.clear(),Dt.set(r,t)),t},ge=(r,t)=>{if(t===r.ch)return!0;if(!r.re)return!1;let e=t.charCodeAt(0);if(e>=128)return r.re.test(t);let s=r.ascii??=new Uint8Array(128);return s[e]||=r.re.test(t)?1:2,s[e]===1},ci=(r,t,e,s,i)=>{let n=[];for(let o=0;o{let t=new Map,e=[];return r.forEach((s,i)=>{s.t==="open"?e.push(i):s.t==="close"&&e.length&&t.set(e.pop(),i)}),t},Qe=(r,t,e,s,i)=>{let n=[],o=[n];for(let h=e;h{let e=[],s="",i=()=>{for(let n of s.normalize(t))e.push(Z(n));s=""};for(let n of r){if(n.t==="lit"){s+=n.ch;continue}i(),e.push(n.t==="ext"?{...n,alts:n.alts.map(o=>ts(o,t))}:n)}return i(),e},ui=(r,t)=>{let e=1,s=h=>({t:"split",id:e++,out:h}),i=(h,a)=>h.reduceRight((l,c)=>n(c,l),a),n=(h,a)=>{switch(h.t){case"lit":let u=t?Ze(h.ch):void 0;return{t:"lit",id:e++,ch:h.ch,re:u,next:a};case"any":case"star":return{t:h.t,id:e++,next:a};case"class":return{t:"class",id:e++,re:h.re,next:a}}let l=u=>h.alts.map(p=>i(p,u));switch(h.type){case"@":return s(l(a));case"?":return s([a,...l(a)]);case"!":return{t:"neg",id:e++,sub:s(l(de)),next:a}}let c=s([]),f=s(l(c));return c.out.push(a,f),h.type==="*"?c:f};return[i(r,de),e]},di=r=>{let t=[],e=new Set,s=n=>n.t==="match"?"match":String(n.id),i=(n,o)=>{if(n.t==="match"||e.has(n))return;e.add(n);let h=a=>t.push(`${o}${n.id}: ${a}`);switch(n.t){case"split":h(`split -> ${n.out.map(s).join(", ")}`);for(let a of n.out)i(a,o);return;case"neg":return h(`!(${s(n.sub)}) -> ${s(n.next)}`),i(n.sub,o+"  "),i(n.next,o);case"lit":h(`${JSON.stringify(n.ch)} -> ${s(n.next)}`);break;case"class":h(`${n.re} -> ${s(n.next)}`);break;default:h(`${n.t==="any"?"?":"*"} -> ${s(n.next)}`)}i(n.next,o)};return i(r,""),[`start -> ${s(r)}`,...t].join(`
+`)},pe=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(t){this.gen=t}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},es=(r,t)=>r.ids.length!==t.ids.length||r.runs.length!==t.runs.length||r.ids.some((e,s)=>e!==t.ids[s])?!1:r.runs.every(e=>t.runs.some(s=>s.neg===e.neg&&es(s.state,e.state))),Xe=r=>({has:new Float64Array(r),seen:new Float64Array(r),gen:0}),dt=class{dots;dotStart;#t;constructor(t,e,s){this.dots=t,this.dotStart=e,this.#t=s}state(){return new pe(++this.#t.gen)}done(t){return t.ids=t.threads.map(e=>e.id).sort((e,s)=>e-s),t.match&&t.ids.unshift(de.id),t}#n(t,e){let{seen:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,!0)}#i(t,e){let{has:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,t.threads.push(e),!0)}restricted(t,e){return e&&(this.dots||this.dotStart&&t===0)}add(t,e,s,i){switch(e.t){case"split":if(!this.#n(t,e))return;for(let o of e.out)this.add(t,o,s,i);return;case"neg":if(!this.#n(t,e))return;let n=this.state();return this.add(n,e.sub,s,!1),this.done(n),this.addRun(t,{t:"run",neg:e,state:n},s,i);case"star":if(this.restricted(s,i))return;this.#i(t,e)&&this.add(t,e.next,s,i);return;case"match":t.match=!0;return;default:this.#i(t,e)}}addRun(t,e,s,i){for(let n of t.runs)if(n.neg===e.neg&&es(n.state,e.state))return;t.runs.push(e),e.state.match||this.add(t,e.neg.next,s,i)}step(t,e,s,i){let n=this.state();for(let o of t.threads)switch(o.t){case"lit":ge(o,e)&&this.add(n,o.next,s+1,i);break;case"any":this.restricted(s,i)||this.add(n,o.next,s+1,i);break;case"class":!this.restricted(s,i)&&o.re.test(e)&&this.add(n,o.next,s+1,i);break;case"star":this.restricted(s,i)||this.add(n,o,s+1,i)}if(!this.restricted(s,i))for(let o of t.runs){if(o.state.dead){this.addRun(n,o,s+1,i);continue}let h=this.step(o.state,e,s,!1);this.addRun(n,{t:"run",neg:o.neg,state:h},s+1,i)}return this.done(n)}},ss=r=>{let t=r.ids.join();if(!r.runs.length)return t;let e=r.runs.map(s=>`${s.neg.id}(${ss(s.state)})`);return`${t}|${e.sort().join("|")}`},pi=1<<18,me=class{#t;#n=new Map;#i=0;#o;#r;#d;#u;constructor(t,e){this.#t=t,this.#d=new dt(!1,!1,e),this.#u=new dt(!1,!0,e)}#f(t){return{state:t,match:t.match,dead:t.dead,next:new Map}}#h(t){let e=ss(t),s=this.#n.get(e);if(s)return s;this.#i>pi&&this.#m();let i=this.#f(t);return this.#n.set(e,i),this.#i+=e.length+1,i}#m(){this.#n.clear(),this.#i=0,this.#o=void 0,this.#r=void 0}start(t){if(t){if(this.#r)return this.#r;let s=this.#u.state();return this.#u.add(s,this.#t,0,!0),this.#r=this.#f(this.#u.done(s))}if(this.#o)return this.#o;let e=this.#d.state();return this.#d.add(e,this.#t,0,!0),this.#o=this.#h(this.#d.done(e))}next(t,e){let s=e.charCodeAt(0),i=s<128?void 0:t.next.get(e);if(i)return i;let n=t===this.#r?this.#h(this.#u.step(t.state,e,0,!0)):this.#h(this.#d.step(t.state,e,1,!0));return s<128?(t.ascii||(t.ascii=new Array(128),this.#i+=128),t.ascii[s]=n):t.next.set(e,n),this.#i++,n}},mi=r=>{let t=[];for(let e=r;e.t!=="match";e=e.next){if(e.t==="split"||e.t==="neg")return;t.push(e)}return t},gi=(r,t,e,s)=>{let i=0,n=e,o=-1,h=0;for(;n{let t=0,e=0;for(let s of r){let[i,n]=wi(s);t+=i,e+=n}return[t,e]},wi=r=>{if(r.t==="star")return[0,1/0];if(r.t!=="ext")return[1,1];if(r.type==="!")return[0,1/0];let t=r.alts.map(is),e=Math.min(...t.map(n=>n[0])),s=Math.max(...t.map(n=>n[1])),i=s===0?0:1/0;return r.type==="@"?[e,s]:r.type==="?"?[0,s]:r.type==="*"?[0,i]:[e,i]},Ve=(r,t,e)=>{for(let s=0;syi.test(r)?[...r]:r,Ye=r=>{if(r.includes("/"))throw new Error("can only match a single path portion, got: "+r)},pt=class{pattern;options;#t;#n;#i;#o;#r;#d=!1;#u;#f;#h=!1;#m=0;#l=1/0;#a=[];#s=[];#b;#E;#y=!1;#g;#w;constructor(t,e={}){if(t.includes("/"))throw new Error("can only match a single path portion, got pattern: "+t);this.pattern=t,this.options=e;let{nocase:s=!1,noext:i=!1,normalize:n}=e;this.#w=n===!0?"NFC":n||void 0;let o=/^[?*+@]\(\)$/.test(t),h=ci(t,s,i||o,this.#w,e.rangeMark),[a]=Qe(h,fi(h),0,h.length,!0);this.#w&&(a=ts(a,this.#w));let[l,c]=ui(a,s);if(this.#t=l,this.#n=c,a.every(f=>f.t==="lit"))this.#r=a.map(f=>f.ch).join(""),this.#d=s;else{let f=g=>g.t!=="lit"?void 0:s?{ch:g.ch,re:Ze(g.ch)}:{ch:g.ch};for(let g of a){let d=f(g);if(!d)break;this.#a.push(d)}for(let g=a.length-1;g>=0;g--){let d=f(a[g]);if(!d)break;this.#s.unshift(d)}this.#y=!!(this.#a.length||this.#s.length),s||(this.#b=this.#a.map(g=>g.ch).join(""),this.#E=this.#s.map(g=>g.ch).join("")),this.#f=mi(this.#t)?.slice(this.#a.length,-this.#s.length||void 0),this.#h=!!this.#f?.every(g=>g.t==="star"||g.t==="any");let[u,p]=is(a);this.#m=u,this.#l=p}}test(t){return this.#w?(Ye(t),this.#p(t.normalize(this.#w))):bi.test(t)?(Ye(t),this.#p(t,[...t])):this.#p(t,t)}testUnchecked(t){return this.#p(this.#w?t.normalize(this.#w):t)}#p(t,e){if(this.#r!==void 0)return this.#d?(this.#u??=Je(this.#r)).test(t):t===this.#r;let s=this.#m,i=this.#l;if(e===void 0){let c=t.length,f=c+1>>1;if(ci)return!1;(fi)&&(e=Nt(t))}if(e!==void 0&&(e.lengthi))return!1;let n=this.#a.length;if(this.#y)if(this.#b!==void 0&&this.#E!==void 0){if(!t.startsWith(this.#b)||!t.endsWith(this.#E))return!1}else{e??=Nt(t);let c=e.length-this.#s.length;if(!Ve(this.#a,e,0)||!Ve(this.#s,e,c))return!1}let o=!this.options.dot&&t.startsWith(".");if(this.#f){if(t==="."||t===".."||o&&!n)return!1;if(this.#h)return!0;e??=Nt(t);let c=e.length-this.#s.length;return gi(this.#f,e,n,c)}if(e??=Nt(t),t==="."||t===".."){this.#i??=Xe(this.#n);let c=this.#o??=new dt(!0,!1,this.#i),f=c.state();c.add(f,this.#t,0,!0);let u=c.done(f);for(let p=0;p{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var K=(r,{windowsPathsNoEscape:t=!1,magicalBraces:e=!1}={})=>e?t?r.replace(/[?*()[\]{}]/g,"[$&]"):r.replace(/[?*()[\]\\{}]/g,"\\$&"):t?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var st=(r,{windowsPathsNoEscape:t=!1,magicalBraces:e=!0}={})=>e?t?r.replace(/\[([^/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):t?r.replace(/\[([^/\\{}])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var T=(r,t,e={})=>(mt(t),!e.nocomment&&t.charAt(0)==="#"?!1:xi(t,e).match(r)),it=new Map,Si=256,xi=(r,t)=>{let e=r+"\0"+JSON.stringify(t),s=it.get(e);return s?it.delete(e):(s=new D(r,{...t}),it.size>=Si&&it.delete(it.keys().next().value)),it.set(e,s),s},ls=typeof process=="object"&&process?process.env?.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ns={win32:{sep:"\\"},posix:{sep:"/"}},vi=ls==="win32"?ns.win32.sep:ns.posix.sep;T.sep=vi;var v=Symbol("globstar **");T.GLOBSTAR=v;var Ei=(r,t={})=>e=>T(e,r,t);T.filter=Ei;var U=(r,t={})=>Object.assign({},r,t),ki=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return T;let t=T;return Object.assign((s,i,n={})=>t(s,i,U(r,n)),{Minimatch:class extends t.Minimatch{constructor(i,n={}){super(i,U(r,n))}static defaults(i){return t.defaults(U(r,i)).Minimatch}},unescape:(s,i={})=>t.unescape(s,U(r,i)),escape:(s,i={})=>t.escape(s,U(r,i)),filter:(s,i={})=>t.filter(s,U(r,i)),defaults:s=>t.defaults(U(r,s)),braceExpand:(s,i={})=>t.braceExpand(s,U(r,i)),match:(s,i,n={})=>t.match(s,i,U(r,n)),sep:t.sep,GLOBSTAR:v})};T.defaults=ki;var xe=(r,t={})=>(mt(r),t.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:Ge(r,{max:t.braceExpandMax}));T.braceExpand=xe;var Ci=100,Ai=/(?{let s=new D(t,e);return r=r.filter(i=>s.match(i)),s.options.nonull&&!r.length&&r.push(t),r};T.match=Mi;var rs=/[?*]|[+@!]\(.*?\)|\[|\]/,cs=(r,t)=>{let e=t+1;(r.charAt(e)==="!"||r.charAt(e)==="^")&&e++;let s=!1;for(;e{if(!t&&(r==="+()"||r==="@()"))return r;let e="";for(let s=0;s{if(/^[?*+@]\(\)$/.test(r)||r.includes("[:"))return!1;let t=0;for(let e=0;etypeof r=="string"?t===r:t!==""&&r.testUnchecked(t),hs=(r,t,e,s,i)=>X(r,t)?e:s!==void 0&&X(r,s)?i:-1,ve=r=>r==="."||r==="..",be=r=>typeof r=="string"&&/^[a-z]:$/i.test(r),zt=r=>typeof r=="string"&&/^unc$/i.test(r),ye=r=>{if(r[0]!==""||r[1]!=="")return-1;let t=r[2]!=="?"?2:zt(r[3])?4:-1,e=r[t],s=r[t+1];return t!==-1&&e!==void 0&&e!==""&&e!==v&&s!==void 0&&s!==""&&s!==v?t:-1},Pt=(r,t)=>!ve(r)&&(t||!r.startsWith(".")),gt=(r,t,e,s,i)=>{for(let n=t;n=e||Lt(r.charCodeAt(h),i))return!0}let o=Ee(r,n,i);if(o===-1)return!1;for(n=o+1;nt==="/"?r===47:t==="\\"?r===92:r===47||r===92,Ee=(r,t,e)=>{if(e!=="both")return r.indexOf(e,t);let s=r.indexOf("/",t),i=r.indexOf("\\",t);return s===-1?i:i===-1?s:Math.min(s,i)},as=(r,t,e)=>e!=="both"?r.lastIndexOf(e,t):Math.max(r.lastIndexOf("/",t),r.lastIndexOf("\\",t)),Se={},D=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;#t;#n;#i;#o;#r=[];#d=[];#u=[];#f=new Map;#h=!1;#m;#l=new WeakMap;constructor(t,e={}){mt(t),e=e||{},this.options=e,this.maxGlobstarRecursion=e.maxGlobstarRecursion??200,this.pattern=t,this.platform=e.platform||ls,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.#t=!this.preserveMultipleSlashes,this.#i=(e.optimizationLevel??1)>=2;let i=e.normalize;this.#o=i===!0?"NFC":i||void 0,this.make();let n=this.set.map(o=>this.#s(o));this.#u=this.set.map((o,h)=>this.#t&&o.length-1>n[h]),this.#r=this.set.map((o,h)=>{let a=this.#u[h]?o.length-1:o.length,l=o.slice(n[h]+1,a).filter(c=>typeof c=="string"&&!!c);return[...new Set(l)]}),this.#n=this.#r.some(o=>o.length),this.#d=this.set.map((o,h)=>{let[a,l,c]=o;if(this.#u[h]&&o.length===2&&a===v&&l!==v)return"tail";if(this.#u[h]&&e.matchBase&&o.length===1&&a!==v&&a!=="")return"base";if(!(!this.#t||n[h]!==-1)){if(o.length===3&&a===v&&c===v&&l!==v&&l!==""&&this.maxGlobstarRecursion>0)return"mid";if(o.length===2&&l===v&&a!==v&&a!=="")return"head"}})}#a(t){return this.#o?t.normalize(this.#o):t}#s(t){if(!this.isWindows)return-1;if(be(t[0]))return 0;if(t[0]===""&&t[1]===""&&t[2]==="?"&&be(t[3]))return 3;let s=ye(t);return s===-1?-1:s+1}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.#M())];let s=this.globSet.map(n=>this.#e(n));this.globParts=this.preprocess(s),this.#h=!0;let i=this.globParts.map((n,o,h)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=n[2]==="?"&&zt(n[3])?6:4,l=n[0]===""&&n[1]===""&&(n[2]==="?"||!rs.test(n[2]))&&n.slice(3,a).every(f=>!rs.test(f)),c=/^[a-z]:/i.test(n[0]);if(l)return[...n.slice(0,a).map(f=>this.#a(f)),...n.slice(a).map(f=>this.parse(f))];if(c)return[this.#a(n[0]),...n.slice(1).map(f=>this.parse(f))]}return n.map(a=>this.parse(a))});if(this.set=i.filter(n=>n.indexOf(!1)===-1),this.isWindows)for(let n=0;n{for(let h=0;hs.length));for(let s=0;s{if(!(o[s]instanceof pt||o[s]===Se)||!Oi(this.globParts[h][s]))return;let a=[...this.globParts[h]];a[s]="";let l=`${o.length}/${a.join("/")}`,c=i.get(l);c?c.push(h):i.set(l,[h])});let n=new Set;for(let o of i.values()){if(o.length<2)continue;let[h,...a]=o,c=`@(${o.map(f=>this.globParts[f][s]).join("|")})`;this.globParts[h][s]=c,this.set[h][s]=this.parse(c);for(let f of a)n.add(f)}n.size&&(t=!0,this.set=this.set.filter((o,h)=>!n.has(h)),this.globParts=this.globParts.filter((o,h)=>!n.has(h)))}}}preprocess(t){if(this.options.noglobstar)for(let s of t)for(let i=0;i=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>{let s=this.#s(e)+1;return e=e.reduce((i,n)=>{let o=i[i.length-1];return n==="**"&&o==="**"?i:n===".."&&i.length>s&&o&&o!==".."&&o!=="."&&o!=="**"?(i.pop(),i):(i.push(n),i)},[]),e.length===0?[""]:e})}#b(t){let e=!this.isWindows||!t.includes("\\")?"/":t.includes("/")?"both":"\\",s=this.#t?0:-1,i="",n=0,o,h=0,a=!!this.options.dot;t:for(let l=0;l=0){let m=d;for(;m>0&&Lt(t.charCodeAt(m-1),e);)m--;h=m===0?0:as(t,m-1,e)+1,o=t.slice(h,m)}let w=this.#i&&(ve(i)||i===""&&o!==void 0&&ve(o));s=w?-1:1,u=!w}let p=-1;if(u&&typeof f=="string"&&(p=hs(f,i,n,o,h),p===-1))continue;if(this.#n){for(let d of this.#r[l])if(!t.includes(d))continue t}if(u&&typeof f=="object"&&(p=hs(f,i,n,o,h),p===-1))continue;let g=this.#d[l];if(g==="base"&&u)return"yes";if(g==="tail"&&u){if(this.#i&>(t,0,p,!0,e))return"maybe";if(!gt(t,0,p,a,e))return"yes";continue}if(g==="mid"||g==="head"){let d=this.#y(t,c,g==="head",a,e);if(d!=="no")return d;continue}return"maybe"}return"no"}#E(t,e,s){let i=!!this.options.dot,n=t.length;if(s==="head"){if(n<2||!X(e[0],t[0]))return!1;for(let h=1;hh&&o.testUnchecked(t.slice(h,a)))&&!gt(t,l,t.length,i,n))return"yes";if(s||gt(t,h,l,i,n))return"no";h=l}return"no"}#g(t){let e=we;return e?.f===t&&e.isWindows===this.isWindows&&e.preserveMultipleSlashes===this.preserveMultipleSlashes&&e.normalize===this.#o?e:void 0}#w(t){let{isWindows:e,preserveMultipleSlashes:s}=this,i=this.#e(e?t.split("\\").join("/"):t),n=this.#o;return n&&(i=i.map(o=>o.normalize(n))),we={f:t,isWindows:e,preserveMultipleSlashes:s,normalize:n,parts:i},we}#p(t){let e=[...t],s=!1;do{if(s=!1,!this.preserveMultipleSlashes){for(let o=1;oh&&o.splice(h+1,c-h);let f=o[h+1],u=o[h+2],p=o[h+3];if(f!==".."||!u||u==="."||u===".."||!p||p==="."||p==="..")continue;let g=o.length-1;if(t.length>=e||s+g>i)throw new RangeError("optimizationLevel 2: too many patterns from '**/..'");n=!0,o.splice(h,1);let d=o.slice(0);d[h]="**",s+=g,t.push(d),h--}if(!this.preserveMultipleSlashes){for(let c=1;c{let h=o.join("/");return e.has(h)?!1:(e.add(h),!0)}),i=new Map;for(let o of s){let h=[];for(let a=0;a1e5)return s;let{dot:n}=this.options;return s.filter(o=>{for(let h of i.values()){if(h[h.length-1]>=o.length)continue;let a=[...o],l=!0,c=!1;for(let f of h){let u=o[f];if(u!=="*"){if(!u||u==="**"||!n&&u.startsWith(".")){l=!1;break}a[f]="*",c=!0}}if(l&&c&&e.has(a.join("/")))return!1}return!0})}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,s=0;for(let i=0;it.length)return!1;let f=t.length-a.length;if(this.#S(t,a,s,f,0))c=a.length;else{if(t[t.length-1]!==""||i+a.length===t.length||(f--,!this.#S(t,a,s,f,0)))return!1;c=a.length+1}}if(!h.length){let f=!!c;for(let u=i;u{m[1]=g-d[b]});let w={head:l,body:c,tail:f,segments:u};return i[n]=w,w}#v(t,e,s,i,n,o,h,a,l){let c=e[n];if(!c){if(o)return i>=s||i===s-1&&t[i]==="";for(let g=i;g63743)return this.braceExpand();let s=String.fromCharCode(e),i=!1,n=t.replace(Ai,(h,a,l)=>{let c=Number(a),f=Number(l);return!Number.isSafeInteger(c)||!Number.isSafeInteger(f)||Math.abs(c-f)+1=0;l--)a=n[l];for(let l=0;lM.hasSubscribers||wt.hasSubscribers,us=new Set,fs=typeof process=="object"&&process?process:{},Di=(r,t,e,s)=>{typeof fs.emitWarning=="function"?fs.emitWarning(r,t,e,s):console.error(`[${e}] ${t}: ${r}`)},Ni=r=>!us.has(r),V=r=>!!r&&r===Math.floor(r)&&r>0&&isFinite(r),ds=r=>V(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?jt:null:null,jt=class extends Array{constructor(r){super(r),this.fill(0)}},Pi=class bt{heap;length;static#t=!1;static create(t){let e=ds(t);if(!e)return[];bt.#t=!0;let s=new bt(t,e);return bt.#t=!1,s}constructor(t,e){if(!bt.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},yt=class ps{#t;#n;#i;#o;#r;#d;#u;#f;get perf(){return this.#f}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#h;#m;#l;#a;#s;#b;#E;#y;#g;#w;#p;#k;#C;#x;#v;#S;#M;#e;#T;static unsafeExposeInternals(t){return{starts:t.#C,ttls:t.#x,autopurgeTimers:t.#v,sizes:t.#k,keyMap:t.#l,keyList:t.#a,valList:t.#s,next:t.#b,prev:t.#E,get head(){return t.#y},get tail(){return t.#g},free:t.#w,isBackgroundFetch:e=>t.#c(e),backgroundFetch:(e,s,i,n)=>t.#L(e,s,i,n),moveToTail:e=>t.#X(e),indexes:e=>t.#O(e),rindexes:e=>t.#F(e),isStale:e=>t.#A(e)}}get max(){return this.#t}get maxSize(){return this.#n}get calculatedSize(){return this.#m}get size(){return this.#h}get fetchMethod(){return this.#d}get memoMethod(){return this.#u}get dispose(){return this.#i}get onInsert(){return this.#o}get disposeAfter(){return this.#r}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:h,allowStale:a,dispose:l,onInsert:c,disposeAfter:f,noDisposeOnSet:u,noUpdateTTL:p,maxSize:g=0,maxEntrySize:d=0,sizeCalculation:w,fetchMethod:m,memoMethod:b,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:q,ignoreFetchAbort:W,backgroundFetchSize:B=1,perf:et}=t;if(this.backgroundFetchSize=B,et!==void 0&&typeof et?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#f=et??_i,e!==0&&!V(e))throw new TypeError("max option must be a nonnegative integer");let ie=e?ds(e):Array;if(!ie)throw new Error("invalid max value: "+e);if(this.#t=e,this.#n=g,this.maxEntrySize=d||this.#n,this.sizeCalculation=w,this.sizeCalculation){if(!this.#n&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#u=b,m!==void 0&&typeof m!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#d=m,this.#M=!!m,this.#l=new Map,this.#a=Array.from({length:e}).fill(void 0),this.#s=Array.from({length:e}).fill(void 0),this.#b=new ie(e),this.#E=new ie(e),this.#y=0,this.#g=0,this.#w=Pi.create(e),this.#h=0,this.#m=0,typeof l=="function"&&(this.#i=l),typeof c=="function"&&(this.#o=c),typeof f=="function"?(this.#r=f,this.#p=[]):(this.#r=void 0,this.#p=void 0),this.#S=!!this.#i,this.#T=!!this.#o,this.#e=!!this.#r,this.noDisposeOnSet=!!u,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!y,this.allowStaleOnFetchAbort=!!q,this.ignoreFetchAbort=!!W,this.maxEntrySize!==0){if(this.#n!==0&&!V(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!V(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!h,this.ttlResolution=V(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!V(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#_()}if(this.#t===0&&this.ttl===0&&this.#n===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#n){let ne="LRU_CACHE_UNBOUNDED";Ni(ne)&&(us.add(ne),Di("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",ne,ps))}}getRemainingTTL(t){return this.#l.has(t)?1/0:0}#_(){let t=new jt(this.#t),e=new jt(this.#t);this.#x=t,this.#C=e;let s=this.ttlAutopurge?Array.from({length:this.#t}):void 0;this.#v=s,this.#W=(a,l,c=this.#f.now())=>{e[a]=l!==0?c:0,t[a]=l,i(a,l)},this.#R=a=>{e[a]=t[a]!==0?this.#f.now():0,i(a,t[a])};let i=this.ttlAutopurge?(a,l)=>{if(s?.[a]&&(clearTimeout(s[a]),s[a]=void 0),l&&l!==0&&s){let c=setTimeout(()=>{this.#A(a)?(this.#j(this.#a[a],"expire"),s[a]=void 0):i(a,h(a))},l+1);c.unref&&c.unref(),s[a]=c}}:()=>{};this.#D=(a,l)=>{if(t[l]){let c=t[l],f=e[l];if(!c||!f)return;a.ttl=c,a.start=f,a.now=n||o();let u=a.now-f;a.remainingTTL=c-u}};let n=0,o=()=>{let a=this.#f.now();if(this.ttlResolution>0){n=a;let l=setTimeout(()=>n=0,this.ttlResolution);l.unref&&l.unref()}return a};this.getRemainingTTL=a=>{let l=this.#l.get(a);return l===void 0?0:h(l)};let h=a=>{let l=t[a],c=e[a];if(!l||!c)return 1/0;let f=(n||o())-c;return l-f};this.#A=a=>{let l=e[a],c=t[a];return!!c&&!!l&&(n||o())-l>c}}#R=()=>{};#D=()=>{};#W=()=>{};#A=()=>!1;#G(){let t=new jt(this.#t);this.#m=0,this.#k=t,this.#P=e=>{this.#m-=t[e],t[e]=0},this.#$=(e,s,i,n)=>{if(!V(i)){if(this.#c(s))return this.backgroundFetchSize;if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,e),!V(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return i},this.#N=(e,s,i)=>{if(t[e]=s,this.#n){let n=this.#n-t[e];for(;this.#m>n;)this.#U(!0)}this.#m+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#m)}}#P=t=>{};#N=(t,e,s)=>{};#$=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:t=this.allowStale}={}){if(this.#h)for(let e=this.#g;this.#I(e)&&((t||!this.#A(e))&&(yield e),e!==this.#y);)e=this.#E[e]}*#F({allowStale:t=this.allowStale}={}){if(this.#h)for(let e=this.#y;this.#I(e)&&((t||!this.#A(e))&&(yield e),e!==this.#g);)e=this.#b[e]}#I(t){return t!==void 0&&this.#l.get(this.#a[t])===t}*entries(){for(let t of this.#O())this.#s[t]!==void 0&&this.#a[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#a[t],this.#s[t]])}*rentries(){for(let t of this.#F())this.#s[t]!==void 0&&this.#a[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#a[t],this.#s[t]])}*keys(){for(let t of this.#O()){let e=this.#a[t];e!==void 0&&!this.#c(this.#s[t])&&(yield e)}}*rkeys(){for(let t of this.#F()){let e=this.#a[t];e!==void 0&&!this.#c(this.#s[t])&&(yield e)}}*values(){for(let t of this.#O())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}*rvalues(){for(let t of this.#F())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&t(n,this.#a[s],this))return this.#K(this.#a[s],e)}}forEach(t,e=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(e,n,this.#a[s],this)}}rforEach(t,e=this){for(let s of this.#F()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(e,n,this.#a[s],this)}}purgeStale(){let t=!1;for(let e of this.#F({allowStale:!0}))this.#A(e)&&(this.#j(this.#a[e],"expire"),t=!0);return t}info(t){let e=this.#l.get(t);if(e===void 0)return;let s=this.#s[e],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#x&&this.#C){let o=this.#x[e],h=this.#C[e];if(o&&h){let a=o-(this.#f.now()-h);n.ttl=a,n.start=Date.now()}}return this.#k&&(n.size=this.#k[e]),n}dump(){let t=[];for(let e of this.#O({allowStale:!0})){let s=this.#a[e],i=this.#s[e],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#x&&this.#C){o.ttl=this.#x[e];let h=this.#f.now()-this.#C[e];o.start=Math.floor(Date.now()-h)}this.#k&&(o.size=this.#k[e]),t.unshift([s,o])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#f.now()-i}this.#z(e,s.value,s)}}set(t,e,s={}){let{status:i=M.hasSubscribers?{}:void 0}=s;s.status=i,i&&(i.op="set",i.key=t,e!==void 0&&(i.value=e),i.cache=this);let n=this.#z(t,e,s);return i&&M.hasSubscribers&&M.publish(i),n}#z(t,e,s,i){let{ttl:n=this.ttl,start:o,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,c=this.#c(e);if(e===void 0)return l&&(l.set="deleted"),this.delete(t),this;let{noUpdateTTL:f=this.noUpdateTTL}=s;l&&!c&&(l.value=e);let u=this.#$(t,e,s.size||0,a,l);if(this.maxEntrySize&&u>this.maxEntrySize)return this.#j(t,"set"),l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this;let p=this.#h===0?void 0:this.#l.get(t);if(p===void 0)p=this.#h===0?this.#g:this.#w.length!==0?this.#w.pop():this.#h===this.#t?this.#U(!1):this.#h,this.#a[p]=t,this.#s[p]=e,this.#l.set(t,p),this.#b[this.#g]=p,this.#E[p]=this.#g,this.#g=p,this.#h++,this.#N(p,u,l),l&&(l.set="add"),f=!1,this.#T&&!c&&this.#o?.(e,t,"add");else{this.#X(p);let g=this.#s[p];if(e!==g){if(!h)if(this.#c(g)){g!==i&&g.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:d}=g;d!==void 0&&d!==e&&(this.#S&&this.#i?.(d,t,"set"),this.#e&&this.#p?.push([d,t,"set"]))}else this.#S&&this.#i?.(g,t,"set"),this.#e&&this.#p?.push([g,t,"set"]);if(this.#P(p),this.#N(p,u,l),this.#s[p]=e,!c){let d=g&&this.#c(g)?g.__staleWhileFetching:g,w=d===void 0?"add":e!==d?"replace":"update";l&&(l.set=w,d!==void 0&&(l.oldValue=d)),this.#T&&this.onInsert?.(e,t,w)}}else c||(l&&(l.set="update"),this.#T&&this.onInsert?.(e,t,"update"))}if(n!==0&&!this.#x&&this.#_(),this.#x&&(f||this.#W(p,n,o),l&&this.#D(l,p)),!h&&this.#e&&this.#p){let g=this.#p,d;for(;d=g?.shift();)this.#r?.(...d)}return this}pop(){try{for(;this.#h;){let t=this.#s[this.#y];if(this.#U(!0),this.#c(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#p){let t=this.#p,e;for(;e=t?.shift();)this.#r?.(...e)}}}#U(t){let e=this.#y,s=this.#a[e],i=this.#s[e],n=this.#c(i);n&&i.__abortController.abort(new Error("evicted"));let o=n?i.__staleWhileFetching:i;return(this.#S||this.#e)&&o!==void 0&&(this.#S&&this.#i?.(o,s,"evict"),this.#e&&this.#p?.push([o,s,"evict"])),this.#P(e),this.#v?.[e]&&(clearTimeout(this.#v[e]),this.#v[e]=void 0),t&&(this.#a[e]=void 0,this.#s[e]=void 0,this.#w.push(e)),this.#h===1?(this.#y=this.#g=0,this.#w.length=0):this.#y=this.#b[e],this.#l.delete(s),this.#h--,e}has(t,e={}){let{status:s=M.hasSubscribers?{}:void 0}=e;e.status=s,s&&(s.op="has",s.key=t,s.cache=this);let i=this.#V(t,e);return M.hasSubscribers&&M.publish(s),i}#V(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,n=this.#l.get(t);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#A(n))i&&(i.has="stale",this.#D(i,n));else return s&&this.#R(n),i&&(i.has="hit",this.#D(i,n)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{status:s=ke()?{}:void 0}=e;s&&(s.op="peek",s.key=t,s.cache=this),e.status=s;let i=this.#H(t,e);return M.hasSubscribers&&M.publish(s),i}#H(t,e){let{status:s,allowStale:i=this.allowStale}=e,n=this.#l.get(t);if(n===void 0||!i&&this.#A(n)){s&&(s.peek=n===void 0?"miss":"stale");return}let o=this.#s[n],h=this.#c(o)?o.__staleWhileFetching:o;return s&&(h!==void 0?(s.peek="hit",s.value=h):s.peek="miss"),h}#L(t,e,s,i){let n=e===void 0?void 0:this.#s[e];if(this.#c(n))return n;let o=new AbortController,{signal:h}=s;h?.addEventListener("abort",()=>o.abort(h.reason),{signal:o.signal});let a={signal:o.signal,options:s,context:i},l=(d,w=!1)=>{let{aborted:m}=o.signal,b=s.ignoreFetchAbort&&d!==void 0,x=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&d!==void 0);if(s.status&&(m&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,b&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),m&&!b&&!w)return f(o.signal.reason,x);let S=p,y=this.#s[e];return(y===p||y===void 0&&b&&w)&&(d===void 0?S.__staleWhileFetching!==void 0?this.#s[e]=S.__staleWhileFetching:this.#j(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.#z(t,d,a.options,S))),d},c=d=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=d),f(d,!1)),f=(d,w)=>{let{aborted:m}=o.signal,b=m&&s.allowStaleOnFetchAbort,x=b||s.allowStaleOnFetchRejection,S=x||s.noDeleteOnFetchRejection,y=p;if(this.#s[e]===p&&(!S||!w&&y.__staleWhileFetching===void 0?this.#j(t,"fetch"):b||(this.#s[e]=y.__staleWhileFetching)),x)return s.status&&y.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),y.__staleWhileFetching;if(y.__returned===y)throw d},u=(d,w)=>{let m=this.#d?.(t,n,a);o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(d(void 0),s.allowStaleOnFetchAbort&&(d=b=>l(b,!0)))}),m&&m instanceof Promise?m.then(b=>d(b===void 0?void 0:b),w):m!==void 0&&d(m)};s.status&&(s.status.fetchDispatched=!0);let p=new Promise(u).then(l,c),g=Object.assign(p,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#z(t,g,{...a.options,status:void 0}),e=this.#l.get(t)):this.#s[e]=g,g}#c(t){if(!this.#M)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof AbortController}fetch(t,e={}){let s=wt.hasSubscribers,{status:i=ke()?{}:void 0}=e;e.status=i,i&&e.context&&(i.context=e.context);let n=this.#q(t,e);return i&&s&&(i.trace=!0,wt.tracePromise(()=>n,i).catch(()=>{})),n}async#q(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:d,forceRefresh:w=!1,status:m,signal:b}=e;if(m&&(m.op="fetch",m.key=t,w&&(m.forceRefresh=!0),m.cache=this),!this.#M)return m&&(m.fetch="get"),this.#K(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:m});let x={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:h,size:a,sizeCalculation:l,noUpdateTTL:c,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:g,ignoreFetchAbort:p,status:m,signal:b},S=this.#l.get(t);if(S===void 0){m&&(m.fetch="miss");let y=this.#L(t,S,x,d);return y.__returned=y}else{let y=this.#s[S];if(this.#c(y)){let et=s&&y.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",et&&(m.returnedStale=!0)),et?y.__staleWhileFetching:y.__returned=y}let q=this.#A(S);if(!w&&!q)return m&&(m.fetch="hit"),this.#X(S),i&&this.#R(S),m&&this.#D(m,S),y;let W=this.#L(t,S,x,d),B=W.__staleWhileFetching!==void 0&&s;return m&&(m.fetch=q?"stale":"refresh",B&&q&&(m.returnedStale=!0)),B?W.__staleWhileFetching:W.__returned=W}}forceFetch(t,e={}){let s=wt.hasSubscribers,{status:i=ke()?{}:void 0}=e;e.status=i,i&&e.context&&(i.context=e.context);let n=this.#B(t,e);return i&&s&&(i.trace=!0,wt.tracePromise(()=>n,i).catch(()=>{})),n}async#B(t,e={}){let s=await this.#q(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let{status:s=M.hasSubscribers?{}:void 0}=e;e.status=s,s&&(s.op="memo",s.key=t,e.context&&(s.context=e.context),s.cache=this);let i=this.#Z(t,e);return s&&(s.value=i),M.hasSubscribers&&M.publish(s),i}#Z(t,e={}){let s=this.#u;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,status:n,forceRefresh:o,...h}=e;n&&o&&(n.forceRefresh=!0);let a=this.#K(t,h),l=o||a===void 0;if(n&&(n.memo=l?"miss":"hit",l||(n.value=a)),!l)return a;let c=s(t,a,{options:h,context:i});return n&&(n.value=c),this.#z(t,c,h),c}get(t,e={}){let{status:s=M.hasSubscribers?{}:void 0}=e;e.status=s,s&&(s.op="get",s.key=t,s.cache=this);let i=this.#K(t,e);return s&&(i!==void 0&&(s.value=i),M.hasSubscribers&&M.publish(s)),i}#K(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=e,h=this.#l.get(t);if(h===void 0){o&&(o.get="miss");return}let a=this.#s[h],l=this.#c(a);return o&&this.#D(o,h),this.#A(h)?l?(o&&(o.get="stale-fetching"),s&&a.__staleWhileFetching!==void 0?(o&&(o.returnedStale=!0),a.__staleWhileFetching):void 0):(n||this.#j(t,"expire"),o&&(o.get="stale"),s?(o&&(o.returnedStale=!0),a):void 0):(o&&(o.get=l?"fetching":"hit"),this.#X(h),i&&this.#R(h),l?a.__staleWhileFetching:a)}#Y(t,e){this.#E[e]=t,this.#b[t]=e}#X(t){t!==this.#g&&(t===this.#y?this.#y=this.#b[t]:this.#Y(this.#E[t],this.#b[t]),this.#Y(this.#g,t),this.#g=t)}delete(t){return this.#j(t,"delete")}#j(t,e){M.hasSubscribers&&M.publish({op:"delete",delete:e,key:t,cache:this});let s=!1;if(this.#h!==0){let i=this.#l.get(t);if(i!==void 0)if(this.#v?.[i]&&(clearTimeout(this.#v[i]),this.#v[i]=void 0),s=!0,this.#h===1)this.#J(e);else{this.#P(i);let n=this.#s[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#S||this.#e)&&(this.#S&&this.#i?.(n,t,e),this.#e&&this.#p?.push([n,t,e])),this.#l.delete(t),this.#a[i]=void 0,this.#s[i]=void 0,i===this.#g)this.#g=this.#E[i];else if(i===this.#y)this.#y=this.#b[i];else{let o=this.#E[i];this.#b[o]=this.#b[i];let h=this.#b[i];this.#E[h]=this.#E[i]}this.#h--,this.#w.push(i)}}if(this.#e&&this.#p?.length){let i=this.#p,n;for(;n=i?.shift();)this.#r?.(...n)}return s}clear(){return this.#J("delete")}#J(t){for(let e of this.#F({allowStale:!0})){let s=this.#s[e];if(this.#c(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#a[e];this.#S&&this.#i?.(s,i,t),this.#e&&this.#p?.push([s,i,t])}}if(this.#l.clear(),this.#s.fill(void 0),this.#a.fill(void 0),this.#x&&this.#C){this.#x.fill(0),this.#C.fill(0);for(let e of this.#v??[])e!==void 0&&clearTimeout(e);this.#v?.fill(void 0)}if(this.#k&&this.#k.fill(0),this.#y=0,this.#g=0,this.#w.length=0,this.#m=0,this.#h=0,this.#e&&this.#p){let e=this.#p,s;for(;s=e?.shift();)this.#r?.(...s)}}};import{posix as qi,win32 as Ne}from"node:path";import{fileURLToPath as Ki}from"node:url";import{lstatSync as Xi,readdir as Vi,readdirSync as Yi,readlinkSync as Ji,realpathSync as Zi}from"fs";import*as Qi from"node:fs";import{lstat as en,readdir as sn,readlink as nn,realpath as rn}from"node:fs/promises";import{EventEmitter as Te}from"node:events";import ys from"node:stream";import{StringDecoder as zi}from"node:string_decoder";var ms=typeof process=="object"&&process?process:{stdout:null,stderr:null},Li=r=>!!r&&typeof r=="object"&&(r instanceof J||r instanceof ys||ji(r)||Wi(r)),ji=r=>!!r&&typeof r=="object"&&r instanceof Te&&typeof r.pipe=="function"&&r.pipe!==ys.Writable.prototype.pipe,Wi=r=>!!r&&typeof r=="object"&&r instanceof Te&&typeof r.write=="function"&&typeof r.end=="function",G=Symbol("EOF"),H=Symbol("maybeEmitEnd"),Y=Symbol("emittedEnd"),Wt=Symbol("emittingEnd"),St=Symbol("emittedError"),$t=Symbol("closed"),gs=Symbol("read"),It=Symbol("flush"),ws=Symbol("flushChunk"),z=Symbol("encoding"),nt=Symbol("decoder"),k=Symbol("flowing"),xt=Symbol("paused"),rt=Symbol("resume"),C=Symbol("buffer"),F=Symbol("pipes"),A=Symbol("bufferLength"),Ce=Symbol("bufferPush"),Bt=Symbol("bufferShift"),R=Symbol("objectMode"),E=Symbol("destroyed"),Ae=Symbol("error"),Me=Symbol("emitData"),bs=Symbol("emitEnd"),Re=Symbol("emitEnd2"),$=Symbol("async"),Oe=Symbol("abort"),Ut=Symbol("aborted"),vt=Symbol("signal"),Q=Symbol("dataListeners"),_=Symbol("discarded"),Et=r=>Promise.resolve().then(r),$i=r=>r(),Ii=r=>r==="end"||r==="finish"||r==="prefinish",Bi=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,Ui=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),Gt=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[rt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Fe=class extends Gt{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},Gi=r=>!!r.objectMode,Hi=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",J=class extends Te{[k]=!1;[xt]=!1;[F]=[];[C]=[];[R];[z];[$];[nt];[G]=!1;[Y]=!1;[Wt]=!1;[$t]=!1;[St]=null;[A]=0;[E]=!1;[vt];[Ut]=!1;[Q]=0;[_]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Gi(e)?(this[R]=!0,this[z]=null):Hi(e)?(this[z]=e.encoding,this[R]=!1):(this[R]=!1,this[z]=null),this[$]=!!e.async,this[nt]=this[z]?new zi(this[z]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[F]});let{signal:s}=e;s&&(this[vt]=s,s.aborted?this[Oe]():s.addEventListener("abort",()=>this[Oe]()))}get bufferLength(){return this[A]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[R]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[$]}set async(t){this[$]=this[$]||!!t}[Oe](){this[Ut]=!0,this.emit("abort",this[vt]?.reason),this.destroy(this[vt]?.reason)}get aborted(){return this[Ut]}set aborted(t){}write(t,e,s){if(this[Ut])return!1;if(this[G])throw new Error("write after end");if(this[E])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[$]?Et:$i;if(!this[R]&&!Buffer.isBuffer(t)){if(Ui(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Bi(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[R]?(this[k]&&this[A]!==0&&this[It](!0),this[k]?this.emit("data",t):this[Ce](t),this[A]!==0&&this.emit("readable"),s&&i(s),this[k]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[nt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[nt].write(t)),this[k]&&this[A]!==0&&this[It](!0),this[k]?this.emit("data",t):this[Ce](t),this[A]!==0&&this.emit("readable"),s&&i(s),this[k]):(this[A]!==0&&this.emit("readable"),s&&i(s),this[k])}read(t){if(this[E])return null;if(this[_]=!1,this[A]===0||t===0||t&&t>this[A])return this[H](),null;this[R]&&(t=null),this[C].length>1&&!this[R]&&(this[C]=[this[z]?this[C].join(""):Buffer.concat(this[C],this[A])]);let e=this[gs](t||null,this[C][0]);return this[H](),e}[gs](t,e){if(this[R])this[Bt]();else{let s=e;t===s.length||t===null?this[Bt]():typeof s=="string"?(this[C][0]=s.slice(t),e=s.slice(0,t),this[A]-=t):(this[C][0]=s.subarray(t),e=s.subarray(0,t),this[A]-=t)}return this.emit("data",e),!this[C].length&&!this[G]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[G]=!0,this.writable=!1,(this[k]||!this[xt])&&this[H](),this}[rt](){this[E]||(!this[Q]&&!this[F].length&&(this[_]=!0),this[xt]=!1,this[k]=!0,this.emit("resume"),this[C].length?this[It]():this[G]?this[H]():this.emit("drain"))}resume(){return this[rt]()}pause(){this[k]=!1,this[xt]=!0,this[_]=!1}get destroyed(){return this[E]}get flowing(){return this[k]}get paused(){return this[xt]}[Ce](t){this[R]?this[A]+=1:this[A]+=t.length,this[C].push(t)}[Bt](){return this[R]?this[A]-=1:this[A]-=this[C][0].length,this[C].shift()}[It](t=!1){do;while(this[ws](this[Bt]())&&this[C].length);!t&&!this[C].length&&!this[G]&&this.emit("drain")}[ws](t){return this.emit("data",t),this[k]}pipe(t,e){if(this[E])return t;this[_]=!1;let s=this[Y];return e=e||{},t===ms.stdout||t===ms.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[F].push(e.proxyErrors?new Fe(this,t,e):new Gt(this,t,e)),this[$]?Et(()=>this[rt]()):this[rt]()),t}unpipe(t){let e=this[F].find(s=>s.dest===t);e&&(this[F].length===1?(this[k]&&this[Q]===0&&(this[k]=!1),this[F]=[]):this[F].splice(this[F].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[_]=!1,this[Q]++,!this[F].length&&!this[k]&&this[rt]();else if(t==="readable"&&this[A]!==0)super.emit("readable");else if(Ii(t)&&this[Y])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[St]){let i=e;this[$]?Et(()=>i.call(this,this[St])):i.call(this,this[St])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Q]=this.listeners("data").length,this[Q]===0&&!this[_]&&!this[F].length&&(this[k]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Q]=0,!this[_]&&!this[F].length&&(this[k]=!1)),e}get emittedEnd(){return this[Y]}[H](){!this[Wt]&&!this[Y]&&!this[E]&&this[C].length===0&&this[G]&&(this[Wt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[$t]&&this.emit("close"),this[Wt]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==E&&this[E])return!1;if(t==="data")return!this[R]&&!s?!1:this[$]?(Et(()=>this[Me](s)),!0):this[Me](s);if(t==="end")return this[bs]();if(t==="close"){if(this[$t]=!0,!this[Y]&&!this[E])return!1;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[St]=s,super.emit(Ae,s);let n=!this[vt]||this.listeners("error").length?super.emit("error",s):!1;return this[H](),n}else if(t==="resume"){let n=super.emit("resume");return this[H](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let i=super.emit(t,...e);return this[H](),i}[Me](t){for(let s of this[F])s.dest.write(t)===!1&&this.pause();let e=this[_]?!1:super.emit("data",t);return this[H](),e}[bs](){return this[Y]?!1:(this[Y]=!0,this.readable=!1,this[$]?(Et(()=>this[Re]()),!0):this[Re]())}[Re](){if(this[nt]){let e=this[nt].end();if(e){for(let s of this[F])s.dest.write(e);this[_]||super.emit("data",e)}}for(let e of this[F])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[R]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[R]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[R])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[z]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(E,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[_]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[G])return e();let n,o,h=f=>{this.off("data",a),this.off("end",l),this.off(E,c),e(),o(f)},a=f=>{this.off("error",h),this.off("end",l),this.off(E,c),this.pause(),n({value:f,done:!!this[G]})},l=()=>{this.off("error",h),this.off("data",a),this.off(E,c),e(),n({done:!0,value:void 0})},c=()=>h(new Error("stream destroyed"));return new Promise((f,u)=>{o=u,n=f,this.once(E,c),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[_]=!1;let t=!1,e=()=>(this.pause(),this.off(Ae,e),this.off(E,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Ae,e),this.once(E,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[E])return t?this.emit("error",t):this.emit(E),this;this[E]=!0,this[_]=!0,this[C].length=0,this[A]=0;let e=this;return typeof e.close=="function"&&!this[$t]&&e.close(),t?this.emit("error",t):this.emit(E),this}static get isStream(){return Li}};var tn=Zi.native,Ct={lstatSync:Xi,readdir:Vi,readdirSync:Yi,readlinkSync:Ji,realpathSync:tn,promises:{lstat:en,readdir:sn,readlink:nn,realpath:rn}},Cs=r=>!r||r===Ct||r===Qi?Ct:{...Ct,...r,promises:{...Ct.promises,...r.promises}},on=/^\\\\\?\\([a-z]:)\\?$/i,hn=/^\\\\\?\\UNC\\([^\\]+\\[^\\]+)\\?$/i,an=/^\\\\[^\\?]+\\[^\\]+$/,Ss=r=>r.replace(/\//g,"\\").replace(on,"$1\\").replace(hn,"\\\\$1\\").replace(an,"$&\\"),ln=/^[\\/]{2}\?[\\/]unc[\\/][^\\/]+[\\/][^\\/]+(?:[\\/]|$)/i,cn=/^[\\/]{2}\?[\\/](?=[a-z]:)/i,fn=/^[\\/]{2}\?[\\/]unc(?=[\\/][^\\/]+[\\/][^\\/])/i,un=/[\\/]/,P=0,As=1,Ms=2,I=4,Rs=6,Os=8,tt=10,Fs=12,N=15,kt=~N,_e=16,xs=32,At=64,L=128,Ht=256,Kt=512,vs=At|L|Kt,dn=1023,De=r=>r.isFile()?Os:r.isDirectory()?I:r.isSymbolicLink()?tt:r.isCharacterDevice()?Ms:r.isBlockDevice()?Rs:r.isSocket()?Fs:r.isFIFO()?As:P,Es=new yt({max:2**12}),Mt=r=>{let t=Es.get(r);if(t)return t;let e=r.normalize("NFKD");return Es.set(r,e),e},ks=new yt({max:2**12}),qt=r=>{let t=ks.get(r);if(t)return t;let e=Mt(r.toLowerCase());return ks.set(r,e),e},Xt=class extends yt{constructor(){super({max:256})}},Pe=class extends yt{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},Ts=Symbol("PathScurry setAsCwd"),O=class{name;root;roots;parent;nocase;isCWD=!1;#t;#n;get dev(){return this.#n}#i;get mode(){return this.#i}#o;get nlink(){return this.#o}#r;get uid(){return this.#r}#d;get gid(){return this.#d}#u;get rdev(){return this.#u}#f;get blksize(){return this.#f}#h;get ino(){return this.#h}#m;get size(){return this.#m}#l;get blocks(){return this.#l}#a;get atimeMs(){return this.#a}#s;get mtimeMs(){return this.#s}#b;get ctimeMs(){return this.#b}#E;get birthtimeMs(){return this.#E}#y;get atime(){return this.#y}#g;get mtime(){return this.#g}#w;get ctime(){return this.#w}#p;get birthtime(){return this.#p}#k;#C;#x;#v;#S;#M;#e;#T;#_;#R;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=P,s,i,n,o,h){this.name=t,this.#k=n?qt(t):Mt(t),this.#e=e&dn,this.nocase=n,this.roots=i,this.root=s||this,this.#T=o,this.#x=h.fullpath,this.#S=h.relative,this.#M=h.relativePosix,this.parent=h.parent,this.parent?this.#t=this.parent.#t:this.#t=Cs(h.fs)}get fs(){return this.#t}depth(){return this.#C!==void 0?this.#C:this.parent?this.#C=this.parent.depth()+1:this.#C=0}childrenCache(){return this.#T}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#D(i):this.#D(i)}#D(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#T.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#T.set(this,e),this.#e&=~_e,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?qt(t):Mt(t);for(let a of s)if(a.#k===i)return a;let n=this.parent?this.sep:"",o=this.#x?this.#x+n+t:void 0,h=this.newChild(t,P,{...e,parent:this,fullpath:o});return this.canReaddir()||(h.#e|=L),s.push(h),h}relative(){if(this.isCWD)return"";if(this.#S!==void 0)return this.#S;let t=this.name,e=this.parent;if(!e)return this.#S=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#M!==void 0)return this.#M;let t=this.name,e=this.parent;if(!e)return this.#M=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#x!==void 0)return this.#x;let t=this.name,e=this.parent;if(!e)return this.#x=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#x=i}fullpathPosix(){if(this.#v!==void 0)return this.#v;if(this.sep==="/")return this.#v=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#v=`//?/${i}`:this.#v=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#v=s}isUnknown(){return(this.#e&N)===P}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&N)===Os}isDirectory(){return(this.#e&N)===I}isCharacterDevice(){return(this.#e&N)===Ms}isBlockDevice(){return(this.#e&N)===Rs}isFIFO(){return(this.#e&N)===As}isSocket(){return(this.#e&N)===Fs}isSymbolicLink(){return(this.#e&tt)===tt}lstatCached(){return this.#e&xs?this:void 0}readlinkCached(){return this.#_}realpathCached(){return this.#R}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#_)return!0;if(!this.parent)return!1;let t=this.#e&N;return!(t!==P&&t!==tt||this.#e&Ht||this.#e&L)}calledReaddir(){return!!(this.#e&_e)}isENOENT(){return!!(this.#e&L)}isNamed(t){return this.nocase?this.#k===qt(t):this.#k===Mt(t)}async readlink(){let t=this.#_;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#_=s}catch(e){this.#F(e.code);return}}readlinkSync(){let t=this.#_;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#_=s}catch(e){this.#F(e.code);return}}#W(t){this.#e|=_e;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let n=s.slice(0,s.provisional);e?t(null,n):queueMicrotask(()=>t(null,n));return}if(this.#L.push(t),this.#c)return;this.#c=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(n,o)=>{if(n)this.#$(n.code),s.provisional=0;else{for(let h of o)this.#I(h,s);this.#W(s)}this.#q(s.slice(0,s.provisional))})}#B;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#B)await this.#B;else{let s=()=>{};this.#B=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#I(i,t);this.#W(t)}catch(i){this.#$(i.code),t.provisional=0}this.#B=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#I(s,t);this.#W(t)}catch(s){this.#$(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&vs)return!1;let t=N&this.#e;return t===P||t===I||t===tt}shouldWalk(t,e){return(this.#e&I)===I&&!(this.#e&vs)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#R)return this.#R;if(!((Kt|Ht|L)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#R=this.resolve(t)}catch{this.#P()}}realpathSync(){if(this.#R)return this.#R;if(!((Kt|Ht|L)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#R=this.resolve(t)}catch{this.#P()}}[Ts](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#S=s.join(this.sep),i.#M=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#S=void 0,i.#M=void 0,i=i.parent}},Vt=class r extends O{sep="\\";splitSep=un;constructor(t,e=P,s,i,n,o,h){super(t,e,s,i,n,o,h)}newChild(t,e=P,s={}){return new r(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return ln.exec(t)?.[0]??Ne.parse(t).root}getRoot(t){if(t=Ss(t.toUpperCase()),t===this.root.name||/^[\\/]$/.test(t))return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new ot(t,{nocase:this.nocase,fs:this.fs}).root}sameRoot(t,e=this.root.name){return Ss(t.toUpperCase())===e}},Yt=class r extends O{splitSep="/";sep="/";constructor(t,e=P,s,i,n,o,h){super(t,e,s,i,n,o,h)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=P,s={}){return new r(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Jt=class{root;rootPath;roots;cwd;#t;#n;#i;nocase;#o;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:n=16*1024,fs:o=Ct}={}){this.#o=Cs(o),(t instanceof URL||t.startsWith("file://"))&&(t=Ki(t));let h=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(h),this.#t=new Xt,this.#n=new Xt,this.#i=new Pe(n);let a=h.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#o),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,f=e.sep,u=this.rootPath,p=!1;for(let g of a){let d=c--;l=l.child(g,{relative:new Array(d).fill("..").join(f),relativePosix:new Array(d).fill("..").join("/"),fullpath:u+=(p?"":f)+g}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#i}resolve(...t){let e="";for(let n=t.length-1;n>=0;n--){let o=t[n];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let n=t.length-1;n>=0;n--){let o=t[n];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let s=this.#n.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#n.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(n=>n.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,h=[];(!n||n(t))&&h.push(s?t:t.fullpath());let a=new Set,l=(f,u)=>{a.add(f),f.readdirCB((p,g)=>{if(p)return u(p);let d=g.length;if(!d)return u();let w=()=>{--d===0&&u()};for(let m of g)(!n||n(m))&&h.push(s?m:m.fullpath()),i&&m.isSymbolicLink()?m.realpath().then(b=>b?.isUnknown()?b.lstat():b).then(b=>b?.shouldWalk(a,o)?l(b,w):w()):m.shouldWalk(a,o)?l(m,w):w()},!0)},c=t;return new Promise((f,u)=>{l(c,p=>{if(p)return u(p);f(h)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,h=[];(!n||n(t))&&h.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let f of c){(!n||n(f))&&h.push(s?f:f.fullpath());let u=f;if(f.isSymbolicLink()){if(!(i&&(u=f.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(a,o)&&a.add(u)}}return h}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e;(!n||n(t))&&(yield s?t:t.fullpath());let h=new Set([t]);for(let a of h){let l=a.readdirSync();for(let c of l){(!n||n(c))&&(yield s?c:c.fullpath());let f=c;if(c.isSymbolicLink()){if(!(i&&(f=c.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(h,o)&&h.add(f)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,h=new J({objectMode:!0});(!n||n(t))&&h.write(s?t:t.fullpath());let a=new Set,l=[t],c=0,f=()=>{let u=!1;for(;!u;){let p=l.shift();if(!p){c===0&&h.end();return}c++,a.add(p);let g=(w,m,b=!1)=>{if(w)return h.emit("error",w);if(i&&!b){let x=[];for(let S of m)S.isSymbolicLink()&&x.push(S.realpath().then(y=>y?.isUnknown()?y.lstat():y));if(x.length){Promise.all(x).then(()=>g(null,m,!0));return}}for(let x of m)x&&(!n||n(x))&&(h.write(s?x:x.fullpath())||(u=!0));c--;for(let x of m){let S=x.realpathCached()||x;S.shouldWalk(a,o)&&l.push(S)}u&&!h.flowing?h.once("drain",f):d||f()},d=!0;p.readdirCB(g,!0),d=!1}};return f(),h}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof O||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:o}=e,h=new J({objectMode:!0}),a=new Set;(!n||n(t))&&h.write(s?t:t.fullpath());let l=[t],c=0,f=()=>{let u=!1;for(;!u;){let p=l.shift();if(!p){c===0&&h.end();return}c++,a.add(p);let g=p.readdirSync();for(let d of g)(!n||n(d))&&(h.write(s?d:d.fullpath())||(u=!0));c--;for(let d of g){let w=d;if(d.isSymbolicLink()){if(!(i&&(w=d.realpathSync())))continue;w.isUnknown()&&w.lstatSync()}w.shouldWalk(a,o)&&l.push(w)}}u&&!h.flowing&&h.once("drain",f)};return f(),h}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[Ts](e)}},ot=class extends Jt{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;typeof t=="string"&&!t.startsWith("file://")&&(t=t.replace(cn,"").replace(fn,"\\")),super(t,Ne,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return Ne.parse(t).root.toUpperCase()}newRoot(t){return new Vt(this.rootPath,I,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},ht=class extends Jt{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,qi,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new Yt(this.rootPath,I,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Rt=class extends ht{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}},rr=process.platform==="win32"?Vt:Yt,_s=process.platform==="win32"?ot:process.platform==="darwin"?Rt:ht;var pn=r=>r.length>=1,mn=r=>r.length>=1,gn=Symbol.for("nodejs.util.inspect.custom"),at=class r{#t;#n;#i;length;#o;#r;#d;#u;#f;#h;#m=!0;constructor(t,e,s,i){if(!pn(t))throw new TypeError("empty pattern list");if(!mn(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#n=e,this.#i=s,this.#o=i,this.#i===0){if(this.isUNC()){let n=this.#l()?6:4,o=this.#t.slice(0,n),h=this.#n.slice(0,n),a=this.#t.slice(n),l=this.#n.slice(n);a[0]===""&&(a.shift(),l.shift());let c=[...o,""].join("/"),f=[...h,""].join("/");this.#t=[c,...a],this.#n=[f,...l],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#t,[h,...a]=this.#n;o[0]===""&&(o.shift(),a.shift());let l=`${n}/`,c=`${h}/`;this.#t=[l,...o],this.#n=[c,...a],this.length=this.#t.length}}}[gn](){return`Pattern <${this.#n.slice(this.#i).join("/")}>`}pattern(){return this.#t[this.#i]}isString(){return typeof this.#t[this.#i]=="string"}isGlobstar(){return this.#t[this.#i]===v}isMatcher(){return typeof this.#t[this.#i]=="object"}globString(){return this.#d=this.#d||(this.#i===0?this.isAbsolute()?this.#n[0]+this.#n.slice(1).join("/"):this.#n.join("/"):this.#n.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#r!==void 0?this.#r:this.hasMore()?(this.#r=new r(this.#t,this.#n,this.#i+1,this.#o),this.#r.#h=this.#h,this.#r.#f=this.#f,this.#r.#u=this.#u,this.#r):this.#r=null}#l(){let t=this.#t;return t[2]==="?"&&typeof t[3]=="string"&&/^unc$/i.test(t[3])}isUNC(){let t=this.#t,e=this.#l()?4:2;return this.#f!==void 0?this.#f:this.#f=this.#o==="win32"&&this.#i===0&&t[0]===""&&t[1]===""&&typeof t[e]=="string"&&!!t[e]&&typeof t[e+1]=="string"&&!!t[e+1]}isDrive(){let t=this.#t;return this.#u!==void 0?this.#u:this.#u=this.#o==="win32"&&this.#i===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#i===0?t:""}checkFollowGlobstar(){return!(this.#i===0||!this.isGlobstar()||!this.#m)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#m?!1:(this.#m=!1,!0)}};var wn=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",lt=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;slashRoot;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:n,normalize:o,platform:h=wn,root:a,windowsPathsNoEscape:l,allowWindowsEscape:c,braceExpandMax:f=1e4},u){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=h,l=!!l||c===!1,this.mmopts={braceExpandMax:f,dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:n,normalize:o,optimizationLevel:2,platform:h,nocomment:!0,nonegate:!0,windowsPathsNoEscape:l};let p=u?.resolve(a??"/").fullpath()??"/";this.slashRoot=K(p.replace(/\\/g,"/").replace(/\/$/,""),{magicalBraces:!0,windowsPathsNoEscape:l});for(let g of t)this.add(g)}add(t){let e=new D(t,this.mmopts);for(let s=0;si.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},Ft=class r{hasWalkedCache;matches=new Ot;subwalks=new Le;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new ze}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),h=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=n.rest();if(f)n=f;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let a,l,c=!1;for(;typeof(a=n.pattern())=="string"&&(l=n.rest());)i=i.resolve(a),n=l,c=!0;if(a=n.pattern(),l=n.rest(),c){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof a=="string"){let f=a===".."||a===""||a===".";this.matches.add(i.resolve(a),h,f);continue}else if(a===v){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let f=l?.pattern(),u=l?.rest();if(!l||(f===""||f===".")&&!u)this.matches.add(i,h,f===""||f===".");else if(f===".."){let p=i.parent||i;u?this.hasWalkedCache.hasWalked(p,u)||this.subwalks.add(p,u):this.matches.add(p,h,!0)}}else typeof a=="object"&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let n of e)for(let o of s){let h=o.isAbsolute(),a=o.pattern(),l=o.rest();a===v?i.testGlobstar(n,o,l,h):typeof a=="object"?i.testMatcher(n,a,l,h):i.testString(n,a,l,h)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),i);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s)}else typeof n=="object"&&this.testMatcher(t,n,s.rest(),i)}}testMatcher(t,e,s,i){e.testUnchecked(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};var{ABSOLUTE:Zt,IF_DIR:Qt}=Ot,bn=(r,t,e)=>typeof r=="string"?new lt([r],t,e):Array.isArray(r)?new lt(r,t,e):r,te=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#n;#i;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#i=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#n=bn(s.ignore??[],s,e),!this.includeChildMatches&&typeof this.#n.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#o(t){return this.seen.has(t)||!!this.#n?.ignored?.(t)}#r(t){return!!this.#n?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.paused?this.#t.push(t):t()}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s,i;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;i=s}else i=t;let o=i.isUnknown()||this.opts.stat?await i.lstat():i;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let h=await o.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat()}return this.matchCheckTest(o,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#o(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s,i;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;i=s}else i=t;let o=i.isUnknown()||this.opts.stat?i.lstatSync():i;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let h=o.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync()}return this.matchCheckTest(o,e)}matchFinish(t,e){this.#o(t)||this.#d(t,e)}#d(t,e){if(!this.includeChildMatches&&this.#n?.add){let n=`${t.relativePosix()}/**`;this.#n.add(n)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let n=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(n+i)}else{let n=this.opts.posix?t.relativePosix():t.relative(),o=this.opts.dotRelative&&!n.startsWith(`..${this.#i}`)?`.${this.#i}`:"";this.matchEmit(n?o+n+i:`.${i}`)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.#d(i,e)}walkCB(t,e,s){if(this.signal?.aborted)return s();this.walkCB2(t,e,new Ft(this.opts),s)}walkCB2(t,e,s,i){if(this.#r(t)||this.signal?.aborted)return i();if(this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let n=1,o=()=>{--n===0&&i()};for(let[h,a]of s.matches.store)this.#o(h)||(n++,this.match(h,!!(a&Zt),!!(a&Qt)).then(()=>o()));for(let h of s.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;n++;let a=h.readdirCached();h.calledReaddir()?this.walkCB3(h,a,s,o):h.readdirCB((l,c)=>this.walkCB3(h,c,s,o),!0)}o()}walkCB3(t,e,s,i){let n=s.filterEntries(t,e),o=1,h=()=>{--o===0&&i()};for(let[a,l]of n.matches.store)this.#o(a)||(o++,this.match(a,!!(l&Zt),!!(l&Qt)).then(()=>h()));for(let[a,l]of n.subwalks.entries())o++,this.walkCB2(a,l,n.child(),h);h()}walkCBSync(t,e,s){if(this.signal?.aborted)return s();this.walkCB2Sync(t,e,new Ft(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#r(t)||this.signal?.aborted)return i();if(this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let n=1,o=()=>{--n===0&&i()};for(let[h,a]of s.matches.store)this.#o(h)||this.matchSync(h,!!(a&Zt),!!(a&Qt));for(let h of s.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;n++;let a=h.readdirSync();this.walkCB3Sync(h,a,s,o)}o()}walkCB3Sync(t,e,s,i){let n=s.filterEntries(t,e),o=1,h=()=>{--o===0&&i()};for(let[a,l]of n.matches.store)this.#o(a)||this.matchSync(a,!!(l&Zt),!!(l&Qt));for(let[a,l]of n.subwalks.entries())o++,this.walkCB2Sync(a,l,n.child(),h);h()}},Tt=class extends te{matches=[];constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.push(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},_t=class extends te{results;constructor(t,e,s){super(t,e,s),this.results=new J({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var Sn=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",j=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=yn(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");let s=typeof t=="string"?[t]:t;if(this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(s=s.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");s=s.map(l=>l.includes("/")?l:`./**/${l}`)}if(this.pattern=s,this.platform=e.platform||Sn,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let l=e.platform==="win32"?ot:e.platform==="darwin"?Rt:e.platform?ht:_s;this.scurry=new l(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",n={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape},o=this.pattern.map(l=>new D(l,n)),[h,a]=o.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=h.map((l,c)=>{let f=a[c];if(!f)throw new Error("invalid pattern object");return new at(l,f,0,this.platform)})}async walk(){return await new Tt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()}walkSync(){return new Tt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()}stream(){return new _t(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new _t(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var je=(r,t={})=>{for(let e of Array.isArray(r)?r:[r])if(new D(e,t).hasMagic())return!0;return!1};function ee(r,t={}){return new j(r,t).streamSync()}function Ps(r,t={}){return new j(r,t).stream()}function zs(r,t={}){return new j(r,t).walkSync()}async function Ds(r,t={}){return new j(r,t).walk()}function se(r,t={}){return new j(r,t).iterateSync()}function Ls(r,t={}){return new j(r,t).iterate()}var xn=ee,vn=Object.assign(Ps,{sync:ee}),En=se,kn=Object.assign(Ls,{sync:se}),Cn=Object.assign(zs,{stream:ee,iterate:se}),Ns=Object.assign(Ds,{glob:Ds,globSync:zs,sync:Cn,globStream:Ps,stream:vn,globStreamSync:ee,streamSync:xn,globIterate:Ls,iterate:kn,globIterateSync:se,iterateSync:En,Glob:j,hasMagic:je,escape:K,unescape:st});Ns.glob=Ns;export{j as Glob,lt as Ignore,K as escape,Ns as glob,Ls as globIterate,se as globIterateSync,Ps as globStream,ee as globStreamSync,zs as globSync,je as hasMagic,kn as iterate,En as iterateSync,vn as stream,xn as streamSync,Cn as sync,st as unescape};
 //# sourceMappingURL=index.min.js.map
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/index.min.js.map b/mac/patchers/desktop/node_modules/glob/dist/esm/index.min.js.map
index f3dc6123e915947668bca637e5406d9417785992..2bd5817cd0cb9da50fda99aa3c62db94854c8a86 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/index.min.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/index.min.js.map
@@ -1,7 +1,7 @@
 {
   "version": 3,
-  "sources": ["../../node_modules/balanced-match/src/index.ts", "../../node_modules/brace-expansion/src/index.ts", "../../node_modules/minimatch/src/assert-valid-pattern.ts", "../../node_modules/minimatch/src/brace-expressions.ts", "../../node_modules/minimatch/src/unescape.ts", "../../node_modules/minimatch/src/ast.ts", "../../node_modules/minimatch/src/escape.ts", "../../node_modules/minimatch/src/index.ts", "../../src/glob.ts", "../../node_modules/lru-cache/src/index.ts", "../../node_modules/path-scurry/src/index.ts", "../../node_modules/minipass/src/index.ts", "../../src/pattern.ts", "../../src/ignore.ts", "../../src/processor.ts", "../../src/walker.ts", "../../src/has-magic.ts", "../../src/index.ts"],
-  "sourcesContent": ["export const balanced = (\n  a: string | RegExp,\n  b: string | RegExp,\n  str: string,\n) => {\n  const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n  const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n  const r = ma !== null && mb != null && range(ma, mb, str)\n\n  return (\n    r && {\n      start: r[0],\n      end: r[1],\n      pre: str.slice(0, r[0]),\n      body: str.slice(r[0] + ma.length, r[1]),\n      post: str.slice(r[1] + mb.length),\n    }\n  )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n  const m = str.match(reg)\n  return m ? m[0] : null\n}\n\nexport const range = (\n  a: string,\n  b: string,\n  str: string,\n): undefined | [number, number] => {\n  let begs: number[],\n    beg: number | undefined,\n    left: number,\n    right: number | undefined = undefined,\n    result: undefined | [number, number]\n  let ai = str.indexOf(a)\n  let bi = str.indexOf(b, ai + 1)\n  let i = ai\n\n  if (ai >= 0 && bi > 0) {\n    if (a === b) {\n      return [ai, bi]\n    }\n    begs = []\n    left = str.length\n\n    while (i >= 0 && !result) {\n      if (i === ai) {\n        begs.push(i)\n        ai = str.indexOf(a, i + 1)\n      } else if (begs.length === 1) {\n        const r = begs.pop()\n        if (r !== undefined) result = [r, bi]\n      } else {\n        beg = begs.pop()\n        if (beg !== undefined && beg < left) {\n          left = beg\n          right = bi\n        }\n\n        bi = str.indexOf(b, i + 1)\n      }\n\n      i = ai < bi && ai >= 0 ? ai : bi\n    }\n\n    if (begs.length && right !== undefined) {\n      result = [left, right]\n    }\n  }\n\n  return result\n}\n", "import { balanced } from 'balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\./g\n\nexport const EXPANSION_MAX = 100_000\n\nfunction numeric(str: string) {\n  return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n  return str\n    .replace(slashPattern, escSlash)\n    .replace(openPattern, escOpen)\n    .replace(closePattern, escClose)\n    .replace(commaPattern, escComma)\n    .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n  return str\n    .replace(escSlashPattern, '\\\\')\n    .replace(escOpenPattern, '{')\n    .replace(escClosePattern, '}')\n    .replace(escCommaPattern, ',')\n    .replace(escPeriodPattern, '.')\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n  if (!str) {\n    return ['']\n  }\n\n  const parts: string[] = []\n  const m = balanced('{', '}', str)\n\n  if (!m) {\n    return str.split(',')\n  }\n\n  const { pre, body, post } = m\n  const p = pre.split(',')\n\n  p[p.length - 1] += '{' + body + '}'\n  const postParts = parseCommaParts(post)\n  if (post.length) {\n    ;(p[p.length - 1] as string) += postParts.shift()\n    p.push.apply(p, postParts)\n  }\n\n  parts.push.apply(parts, p)\n\n  return parts\n}\n\nexport type BraceExpansionOptions = {\n  max?: number\n}\n\nexport function expand(str: string, options: BraceExpansionOptions = {}) {\n  if (!str) {\n    return []\n  }\n\n  const { max = EXPANSION_MAX } = options\n\n  // I don't know why Bash 4.3 does this, but it does.\n  // Anything starting with {} will have the first two bytes preserved\n  // but *only* at the top level, so {},a}b will not expand to anything,\n  // but a{},b}c will be expanded to [a}c,abc].\n  // One could argue that this is a bug in Bash, but since the goal of\n  // this module is to match Bash's rules, we escape a leading {}\n  if (str.slice(0, 2) === '{}') {\n    str = '\\\\{\\\\}' + str.slice(2)\n  }\n\n  return expand_(escapeBraces(str), max, true).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n  return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n  return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n  return i <= y\n}\n\nfunction gte(i: number, y: number) {\n  return i >= y\n}\n\nfunction expand_(str: string, max: number, isTop: boolean): string[] {\n  /** @type {string[]} */\n  const expansions: string[] = []\n\n  const m = balanced('{', '}', str)\n  if (!m) return [str]\n\n  // no need to expand pre, since it is guaranteed to be free of brace-sets\n  const pre = m.pre\n  const post: string[] = m.post.length ? expand_(m.post, max, false) : ['']\n\n  if (/\\$$/.test(m.pre)) {\n    for (let k = 0; k < post.length && k < max; k++) {\n      const expansion = pre + '{' + m.body + '}' + post[k]\n      expansions.push(expansion)\n    }\n  } else {\n    const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n    const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(\n      m.body,\n    )\n    const isSequence = isNumericSequence || isAlphaSequence\n    const isOptions = m.body.indexOf(',') >= 0\n    if (!isSequence && !isOptions) {\n      // {a},b}\n      if (m.post.match(/,(?!,).*\\}/)) {\n        str = m.pre + '{' + m.body + escClose + m.post\n        return expand_(str, max, true)\n      }\n      return [str]\n    }\n\n    let n: string[]\n    if (isSequence) {\n      n = m.body.split(/\\.\\./)\n    } else {\n      n = parseCommaParts(m.body)\n      if (n.length === 1 && n[0] !== undefined) {\n        // x{{a,b}}y ==> x{a}y x{b}y\n        n = expand_(n[0], max, false).map(embrace)\n        //XXX is this necessary? Can't seem to hit it in tests.\n        /* c8 ignore start */\n        if (n.length === 1) {\n          return post.map(p => m.pre + n[0] + p)\n        }\n        /* c8 ignore stop */\n      }\n    }\n\n    // at this point, n is the parts, and we know it's not a comma set\n    // with a single entry.\n    let N: string[]\n\n    if (isSequence && n[0] !== undefined && n[1] !== undefined) {\n      const x = numeric(n[0])\n      const y = numeric(n[1])\n      const width = Math.max(n[0].length, n[1].length)\n      let incr =\n        n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1\n      let test = lte\n      const reverse = y < x\n      if (reverse) {\n        incr *= -1\n        test = gte\n      }\n      const pad = n.some(isPadded)\n\n      N = []\n\n      for (let i = x; test(i, y); i += incr) {\n        let c\n        if (isAlphaSequence) {\n          c = String.fromCharCode(i)\n          if (c === '\\\\') {\n            c = ''\n          }\n        } else {\n          c = String(i)\n          if (pad) {\n            const need = width - c.length\n            if (need > 0) {\n              const z = new Array(need + 1).join('0')\n              if (i < 0) {\n                c = '-' + z + c.slice(1)\n              } else {\n                c = z + c\n              }\n            }\n          }\n        }\n        N.push(c)\n      }\n    } else {\n      N = []\n\n      for (let j = 0; j < n.length; j++) {\n        N.push.apply(N, expand_(n[j] as string, max, false))\n      }\n    }\n\n    for (let j = 0; j < N.length; j++) {\n      for (let k = 0; k < post.length && expansions.length < max; k++) {\n        const expansion = pre + N[j] + post[k]\n        if (!isTop || isSequence || expansion) {\n          expansions.push(expansion)\n        }\n      }\n    }\n  }\n\n  return expansions\n}\n", "const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n  pattern: any,\n): asserts pattern is string => {\n  if (typeof pattern !== 'string') {\n    throw new TypeError('invalid pattern')\n  }\n\n  if (pattern.length > MAX_PATTERN_LENGTH) {\n    throw new TypeError('pattern is too long')\n  }\n}\n", "// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } =\n  {\n    '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n    '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n    '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n    '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n    '[:cntrl:]': ['\\\\p{Cc}', true],\n    '[:digit:]': ['\\\\p{Nd}', true],\n    '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n    '[:lower:]': ['\\\\p{Ll}', true],\n    '[:print:]': ['\\\\p{C}', true],\n    '[:punct:]': ['\\\\p{P}', true],\n    '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n    '[:upper:]': ['\\\\p{Lu}', true],\n    '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n    '[:xdigit:]': ['A-Fa-f0-9', false],\n  }\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n  src: string,\n  uFlag: boolean,\n  consumed: number,\n  hasMagic: boolean,\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n  glob: string,\n  position: number,\n): ParseClassResult => {\n  const pos = position\n  /* c8 ignore start */\n  if (glob.charAt(pos) !== '[') {\n    throw new Error('not in a brace expression')\n  }\n  /* c8 ignore stop */\n  const ranges: string[] = []\n  const negs: string[] = []\n\n  let i = pos + 1\n  let sawStart = false\n  let uflag = false\n  let escaping = false\n  let negate = false\n  let endPos = pos\n  let rangeStart = ''\n  WHILE: while (i < glob.length) {\n    const c = glob.charAt(i)\n    if ((c === '!' || c === '^') && i === pos + 1) {\n      negate = true\n      i++\n      continue\n    }\n\n    if (c === ']' && sawStart && !escaping) {\n      endPos = i + 1\n      break\n    }\n\n    sawStart = true\n    if (c === '\\\\') {\n      if (!escaping) {\n        escaping = true\n        i++\n        continue\n      }\n      // escaped \\ char, fall through and treat like normal char\n    }\n    if (c === '[' && !escaping) {\n      // either a posix class, a collation equivalent, or just a [\n      for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n        if (glob.startsWith(cls, i)) {\n          // invalid, [a-[] is fine, but not [a-[:alpha]]\n          if (rangeStart) {\n            return ['$.', false, glob.length - pos, true]\n          }\n          i += cls.length\n          if (neg) negs.push(unip)\n          else ranges.push(unip)\n          uflag = uflag || u\n          continue WHILE\n        }\n      }\n    }\n\n    // now it's just a normal character, effectively\n    escaping = false\n    if (rangeStart) {\n      // throw this range away if it's not valid, but others\n      // can still match.\n      if (c > rangeStart) {\n        ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n      } else if (c === rangeStart) {\n        ranges.push(braceEscape(c))\n      }\n      rangeStart = ''\n      i++\n      continue\n    }\n\n    // now might be the start of a range.\n    // can be either c-d or c-] or c] or c] at this point\n    if (glob.startsWith('-]', i + 1)) {\n      ranges.push(braceEscape(c + '-'))\n      i += 2\n      continue\n    }\n    if (glob.startsWith('-', i + 1)) {\n      rangeStart = c\n      i += 2\n      continue\n    }\n\n    // not the start of a range, just a single character\n    ranges.push(braceEscape(c))\n    i++\n  }\n\n  if (endPos < i) {\n    // didn't see the end of the class, not a valid class,\n    // but might still be valid as a literal match.\n    return ['', false, 0, false]\n  }\n\n  // if we got no ranges and no negates, then we have a range that\n  // cannot possibly match anything, and that poisons the whole glob\n  if (!ranges.length && !negs.length) {\n    return ['$.', false, glob.length - pos, true]\n  }\n\n  // if we got one positive range, and it's a single character, then that's\n  // not actually a magic pattern, it's just that one literal character.\n  // we should not treat that as \"magic\", we should just return the literal\n  // character. [_] is a perfectly valid way to escape glob magic chars.\n  if (\n    negs.length === 0 &&\n    ranges.length === 1 &&\n    /^\\\\?.$/.test(ranges[0]) &&\n    !negate\n  ) {\n    const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n    return [regexpEscape(r), false, endPos - pos, false]\n  }\n\n  const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n  const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n  const comb =\n    ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n    : ranges.length ? sranges\n    : snegs\n\n  return [comb, uflag, endPos - pos, true]\n}\n", "import { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = true,\n  }: Pick = {},\n) => {\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n      : s\n          .replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2')\n          .replace(/\\\\([^\\/])/g, '$1')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/\\[([^\\/\\\\{}])\\]/g, '$1')\n    : s\n        .replace(/((?!\\\\).|^)\\[([^\\/\\\\{}])\\]/g, '$1$2')\n        .replace(/\\\\([^\\/{}])/g, '$1')\n}\n", "// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n//   1   2 3   4 5 6      1   2    3   46      5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n//                                 v----- .* because there's more following,\n//                                 v    v  otherwise, .+ because it must be\n//                                 v    v  *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n//   copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n  types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n  type: ExtglobType | null\n  readonly #root: AST\n\n  #hasMagic?: boolean\n  #uflag: boolean = false\n  #parts: (string | AST)[] = []\n  readonly #parent?: AST\n  readonly #parentIndex: number\n  #negs: AST[]\n  #filledNegs: boolean = false\n  #options: MinimatchOptions\n  #toString?: string\n  // set to true if it's an extglob with no children\n  // (which really means one child of '')\n  #emptyExt: boolean = false\n\n  constructor(\n    type: ExtglobType | null,\n    parent?: AST,\n    options: MinimatchOptions = {},\n  ) {\n    this.type = type\n    // extglobs are inherently magical\n    if (type) this.#hasMagic = true\n    this.#parent = parent\n    this.#root = this.#parent ? this.#parent.#root : this\n    this.#options = this.#root === this ? options : this.#root.#options\n    this.#negs = this.#root === this ? [] : this.#root.#negs\n    if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n    this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n  }\n\n  get hasMagic(): boolean | undefined {\n    /* c8 ignore start */\n    if (this.#hasMagic !== undefined) return this.#hasMagic\n    /* c8 ignore stop */\n    for (const p of this.#parts) {\n      if (typeof p === 'string') continue\n      if (p.type || p.hasMagic) return (this.#hasMagic = true)\n    }\n    // note: will be undefined until we generate the regexp src and find out\n    return this.#hasMagic\n  }\n\n  // reconstructs the pattern\n  toString(): string {\n    if (this.#toString !== undefined) return this.#toString\n    if (!this.type) {\n      return (this.#toString = this.#parts.map(p => String(p)).join(''))\n    } else {\n      return (this.#toString =\n        this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n    }\n  }\n\n  #fillNegs() {\n    /* c8 ignore start */\n    if (this !== this.#root) throw new Error('should only call on root')\n    if (this.#filledNegs) return this\n    /* c8 ignore stop */\n\n    // call toString() once to fill this out\n    this.toString()\n    this.#filledNegs = true\n    let n: AST | undefined\n    while ((n = this.#negs.pop())) {\n      if (n.type !== '!') continue\n      // walk up the tree, appending everthing that comes AFTER parentIndex\n      let p: AST | undefined = n\n      let pp = p.#parent\n      while (pp) {\n        for (\n          let i = p.#parentIndex + 1;\n          !pp.type && i < pp.#parts.length;\n          i++\n        ) {\n          for (const part of n.#parts) {\n            /* c8 ignore start */\n            if (typeof part === 'string') {\n              throw new Error('string part in extglob AST??')\n            }\n            /* c8 ignore stop */\n            part.copyIn(pp.#parts[i])\n          }\n        }\n        p = pp\n        pp = p.#parent\n      }\n    }\n    return this\n  }\n\n  push(...parts: (string | AST)[]) {\n    for (const p of parts) {\n      if (p === '') continue\n      /* c8 ignore start */\n      if (\n        typeof p !== 'string' &&\n        !(p instanceof AST && p.#parent === this)\n      ) {\n        throw new Error('invalid part: ' + p)\n      }\n      /* c8 ignore stop */\n      this.#parts.push(p)\n    }\n  }\n\n  toJSON() {\n    const ret: any[] =\n      this.type === null ?\n        this.#parts\n          .slice()\n          .map(p => (typeof p === 'string' ? p : p.toJSON()))\n      : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n    if (this.isStart() && !this.type) ret.unshift([])\n    if (\n      this.isEnd() &&\n      (this === this.#root ||\n        (this.#root.#filledNegs && this.#parent?.type === '!'))\n    ) {\n      ret.push({})\n    }\n    return ret\n  }\n\n  isStart(): boolean {\n    if (this.#root === this) return true\n    // if (this.type) return !!this.#parent?.isStart()\n    if (!this.#parent?.isStart()) return false\n    if (this.#parentIndex === 0) return true\n    // if everything AHEAD of this is a negation, then it's still the \"start\"\n    const p = this.#parent\n    for (let i = 0; i < this.#parentIndex; i++) {\n      const pp = p.#parts[i]\n      if (!(pp instanceof AST && pp.type === '!')) {\n        return false\n      }\n    }\n    return true\n  }\n\n  isEnd(): boolean {\n    if (this.#root === this) return true\n    if (this.#parent?.type === '!') return true\n    if (!this.#parent?.isEnd()) return false\n    if (!this.type) return this.#parent?.isEnd()\n    // if not root, it'll always have a parent\n    /* c8 ignore start */\n    const pl = this.#parent ? this.#parent.#parts.length : 0\n    /* c8 ignore stop */\n    return this.#parentIndex === pl - 1\n  }\n\n  copyIn(part: AST | string) {\n    if (typeof part === 'string') this.push(part)\n    else this.push(part.clone(this))\n  }\n\n  clone(parent: AST) {\n    const c = new AST(this.type, parent)\n    for (const p of this.#parts) {\n      c.copyIn(p)\n    }\n    return c\n  }\n\n  static #parseAST(\n    str: string,\n    ast: AST,\n    pos: number,\n    opt: MinimatchOptions,\n  ): number {\n    let escaping = false\n    let inBrace = false\n    let braceStart = -1\n    let braceNeg = false\n    if (ast.type === null) {\n      // outside of a extglob, append until we find a start\n      let i = pos\n      let acc = ''\n      while (i < str.length) {\n        const c = str.charAt(i++)\n        // still accumulate escapes at this point, but we do ignore\n        // starts that are escaped\n        if (escaping || c === '\\\\') {\n          escaping = !escaping\n          acc += c\n          continue\n        }\n\n        if (inBrace) {\n          if (i === braceStart + 1) {\n            if (c === '^' || c === '!') {\n              braceNeg = true\n            }\n          } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n            inBrace = false\n          }\n          acc += c\n          continue\n        } else if (c === '[') {\n          inBrace = true\n          braceStart = i\n          braceNeg = false\n          acc += c\n          continue\n        }\n\n        if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n          ast.push(acc)\n          acc = ''\n          const ext = new AST(c, ast)\n          i = AST.#parseAST(str, ext, i, opt)\n          ast.push(ext)\n          continue\n        }\n        acc += c\n      }\n      ast.push(acc)\n      return i\n    }\n\n    // some kind of extglob, pos is at the (\n    // find the next | or )\n    let i = pos + 1\n    let part = new AST(null, ast)\n    const parts: AST[] = []\n    let acc = ''\n    while (i < str.length) {\n      const c = str.charAt(i++)\n      // still accumulate escapes at this point, but we do ignore\n      // starts that are escaped\n      if (escaping || c === '\\\\') {\n        escaping = !escaping\n        acc += c\n        continue\n      }\n\n      if (inBrace) {\n        if (i === braceStart + 1) {\n          if (c === '^' || c === '!') {\n            braceNeg = true\n          }\n        } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n          inBrace = false\n        }\n        acc += c\n        continue\n      } else if (c === '[') {\n        inBrace = true\n        braceStart = i\n        braceNeg = false\n        acc += c\n        continue\n      }\n\n      if (isExtglobType(c) && str.charAt(i) === '(') {\n        part.push(acc)\n        acc = ''\n        const ext = new AST(c, part)\n        part.push(ext)\n        i = AST.#parseAST(str, ext, i, opt)\n        continue\n      }\n      if (c === '|') {\n        part.push(acc)\n        acc = ''\n        parts.push(part)\n        part = new AST(null, ast)\n        continue\n      }\n      if (c === ')') {\n        if (acc === '' && ast.#parts.length === 0) {\n          ast.#emptyExt = true\n        }\n        part.push(acc)\n        acc = ''\n        ast.push(...parts, part)\n        return i\n      }\n      acc += c\n    }\n\n    // unfinished extglob\n    // if we got here, it was a malformed extglob! not an extglob, but\n    // maybe something else in there.\n    ast.type = null\n    ast.#hasMagic = undefined\n    ast.#parts = [str.substring(pos - 1)]\n    return i\n  }\n\n  static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n    const ast = new AST(null, undefined, options)\n    AST.#parseAST(pattern, ast, 0, options)\n    return ast\n  }\n\n  // returns the regular expression if there's magic, or the unescaped\n  // string if not.\n  toMMPattern(): MMRegExp | string {\n    // should only be called on root\n    /* c8 ignore start */\n    if (this !== this.#root) return this.#root.toMMPattern()\n    /* c8 ignore stop */\n    const glob = this.toString()\n    const [re, body, hasMagic, uflag] = this.toRegExpSource()\n    // if we're in nocase mode, and not nocaseMagicOnly, then we do\n    // still need a regular expression if we have to case-insensitively\n    // match capital/lowercase characters.\n    const anyMagic =\n      hasMagic ||\n      this.#hasMagic ||\n      (this.#options.nocase &&\n        !this.#options.nocaseMagicOnly &&\n        glob.toUpperCase() !== glob.toLowerCase())\n    if (!anyMagic) {\n      return body\n    }\n\n    const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n    return Object.assign(new RegExp(`^${re}$`, flags), {\n      _src: re,\n      _glob: glob,\n    })\n  }\n\n  get options() {\n    return this.#options\n  }\n\n  // returns the string match, the regexp source, whether there's magic\n  // in the regexp (so a regular expression is required) and whether or\n  // not the uflag is needed for the regular expression (for posix classes)\n  // TODO: instead of injecting the start/end at this point, just return\n  // the BODY of the regexp, along with the start/end portions suitable\n  // for binding the start/end in either a joined full-path makeRe context\n  // (where we bind to (^|/), or a standalone matchPart context (where\n  // we bind to ^, and not /).  Otherwise slashes get duped!\n  //\n  // In part-matching mode, the start is:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n  // - if dots allowed or not possible: ^\n  // - if dots possible and not allowed: ^(?!\\.)\n  // end is:\n  // - if not isEnd(): nothing\n  // - else: $\n  //\n  // In full-path matching mode, we put the slash at the START of the\n  // pattern, so start is:\n  // - if first pattern: same as part-matching mode\n  // - if not isStart(): nothing\n  // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n  // - if dots allowed or not possible: /\n  // - if dots possible and not allowed: /(?!\\.)\n  // end is:\n  // - if last pattern, same as part-matching mode\n  // - else nothing\n  //\n  // Always put the (?:$|/) on negated tails, though, because that has to be\n  // there to bind the end of the negated pattern portion, and it's easier to\n  // just stick it in now rather than try to inject it later in the middle of\n  // the pattern.\n  //\n  // We can just always return the same end, and leave it up to the caller\n  // to know whether it's going to be used joined or in parts.\n  // And, if the start is adjusted slightly, can do the same there:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n  // - if dots allowed or not possible: (?:/|^)\n  // - if dots possible and not allowed: (?:/|^)(?!\\.)\n  //\n  // But it's better to have a simpler binding without a conditional, for\n  // performance, so probably better to return both start options.\n  //\n  // Then the caller just ignores the end if it's not the first pattern,\n  // and the start always gets applied.\n  //\n  // But that's always going to be $ if it's the ending pattern, or nothing,\n  // so the caller can just attach $ at the end of the pattern when building.\n  //\n  // So the todo is:\n  // - better detect what kind of start is needed\n  // - return both flavors of starting pattern\n  // - attach $ at the end of the pattern when creating the actual RegExp\n  //\n  // Ah, but wait, no, that all only applies to the root when the first pattern\n  // is not an extglob. If the first pattern IS an extglob, then we need all\n  // that dot prevention biz to live in the extglob portions, because eg\n  // +(*|.x*) can match .xy but not .yx.\n  //\n  // So, return the two flavors if it's #root and the first child is not an\n  // AST, otherwise leave it to the child AST to handle it, and there,\n  // use the (?:^|/) style of start binding.\n  //\n  // Even simplified further:\n  // - Since the start for a join is eg /(?!\\.) and the start for a part\n  // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n  // or start or whatever) and prepend ^ or / at the Regexp construction.\n  toRegExpSource(\n    allowDot?: boolean,\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    const dot = allowDot ?? !!this.#options.dot\n    if (this.#root === this) this.#fillNegs()\n    if (!this.type) {\n      const noEmpty =\n        this.isStart() &&\n        this.isEnd() &&\n        !this.#parts.some(s => typeof s !== 'string')\n      const src = this.#parts\n        .map(p => {\n          const [re, _, hasMagic, uflag] =\n            typeof p === 'string' ?\n              AST.#parseGlob(p, this.#hasMagic, noEmpty)\n            : p.toRegExpSource(allowDot)\n          this.#hasMagic = this.#hasMagic || hasMagic\n          this.#uflag = this.#uflag || uflag\n          return re\n        })\n        .join('')\n\n      let start = ''\n      if (this.isStart()) {\n        if (typeof this.#parts[0] === 'string') {\n          // this is the string that will match the start of the pattern,\n          // so we need to protect against dots and such.\n\n          // '.' and '..' cannot match unless the pattern is that exactly,\n          // even if it starts with . or dot:true is set.\n          const dotTravAllowed =\n            this.#parts.length === 1 && justDots.has(this.#parts[0])\n          if (!dotTravAllowed) {\n            const aps = addPatternStart\n            // check if we have a possibility of matching . or ..,\n            // and prevent that.\n            const needNoTrav =\n              // dots are allowed, and the pattern starts with [ or .\n              (dot && aps.has(src.charAt(0))) ||\n              // the pattern starts with \\., and then [ or .\n              (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n              // the pattern starts with \\.\\., and then [ or .\n              (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n            // no need to prevent dots if it can't match a dot, or if a\n            // sub-pattern will be preventing it anyway.\n            const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n            start =\n              needNoTrav ? startNoTraversal\n              : needNoDot ? startNoDot\n              : ''\n          }\n        }\n      }\n\n      // append the \"end of path portion\" pattern to negation tails\n      let end = ''\n      if (\n        this.isEnd() &&\n        this.#root.#filledNegs &&\n        this.#parent?.type === '!'\n      ) {\n        end = '(?:$|\\\\/)'\n      }\n      const final = start + src + end\n      return [\n        final,\n        unescape(src),\n        (this.#hasMagic = !!this.#hasMagic),\n        this.#uflag,\n      ]\n    }\n\n    // We need to calculate the body *twice* if it's a repeat pattern\n    // at the start, once in nodot mode, then again in dot mode, so a\n    // pattern like *(?) can match 'x.y'\n\n    const repeated = this.type === '*' || this.type === '+'\n    // some kind of extglob\n    const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n    let body = this.#partsToRegExp(dot)\n\n    if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n      // invalid extglob, has to at least be *something* present, if it's\n      // the entire path portion.\n      const s = this.toString()\n      this.#parts = [s]\n      this.type = null\n      this.#hasMagic = undefined\n      return [s, unescape(this.toString()), false, false]\n    }\n\n    // XXX abstract out this map method\n    let bodyDotAllowed =\n      !repeated || allowDot || dot || !startNoDot ?\n        ''\n      : this.#partsToRegExp(true)\n    if (bodyDotAllowed === body) {\n      bodyDotAllowed = ''\n    }\n    if (bodyDotAllowed) {\n      body = `(?:${body})(?:${bodyDotAllowed})*?`\n    }\n\n    // an empty !() is exactly equivalent to a starNoEmpty\n    let final = ''\n    if (this.type === '!' && this.#emptyExt) {\n      final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n    } else {\n      const close =\n        this.type === '!' ?\n          // !() must match something,but !(x) can match ''\n          '))' +\n          (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n          star +\n          ')'\n        : this.type === '@' ? ')'\n        : this.type === '?' ? ')?'\n        : this.type === '+' && bodyDotAllowed ? ')'\n        : this.type === '*' && bodyDotAllowed ? `)?`\n        : `)${this.type}`\n      final = start + body + close\n    }\n    return [\n      final,\n      unescape(body),\n      (this.#hasMagic = !!this.#hasMagic),\n      this.#uflag,\n    ]\n  }\n\n  #partsToRegExp(dot: boolean) {\n    return this.#parts\n      .map(p => {\n        // extglob ASTs should only contain parent ASTs\n        /* c8 ignore start */\n        if (typeof p === 'string') {\n          throw new Error('string type in extglob ast??')\n        }\n        /* c8 ignore stop */\n        // can ignore hasMagic, because extglobs are already always magic\n        const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n        this.#uflag = this.#uflag || uflag\n        return re\n      })\n      .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n      .join('|')\n  }\n\n  static #parseGlob(\n    glob: string,\n    hasMagic: boolean | undefined,\n    noEmpty: boolean = false,\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    let escaping = false\n    let re = ''\n    let uflag = false\n    // multiple stars that aren't globstars coalesce into one *\n    let inStar = false\n    for (let i = 0; i < glob.length; i++) {\n      const c = glob.charAt(i)\n      if (escaping) {\n        escaping = false\n        re += (reSpecials.has(c) ? '\\\\' : '') + c\n        continue\n      }\n      if (c === '*') {\n        if (inStar) continue\n        inStar = true\n        re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star\n        hasMagic = true\n        continue\n      } else {\n        inStar = false\n      }\n      if (c === '\\\\') {\n        if (i === glob.length - 1) {\n          re += '\\\\\\\\'\n        } else {\n          escaping = true\n        }\n        continue\n      }\n      if (c === '[') {\n        const [src, needUflag, consumed, magic] = parseClass(glob, i)\n        if (consumed) {\n          re += src\n          uflag = uflag || needUflag\n          i += consumed - 1\n          hasMagic = hasMagic || magic\n          continue\n        }\n      }\n      if (c === '?') {\n        re += qmark\n        hasMagic = true\n        continue\n      }\n      re += regExpEscape(c)\n    }\n    return [re, unescape(glob), !!hasMagic, uflag]\n  }\n}\n", "import { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character.  In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n */\nexport const escape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = false,\n  }: Pick = {},\n) => {\n  // don't need to escape +@! because we escape the parens\n  // that make those magic, and escaping ! as [!] isn't valid,\n  // because [!]] is a valid glob class meaning not ']'.\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/[?*()[\\]{}]/g, '[$&]')\n      : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/[?*()[\\]]/g, '[$&]')\n    : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n", "import { expand } from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\nexport type Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  /** do not expand `{x,y}` style braces */\n  nobrace?: boolean\n  /** do not treat patterns starting with `#` as a comment */\n  nocomment?: boolean\n  /** do not treat patterns starting with `!` as a negation */\n  nonegate?: boolean\n  /** print LOTS of debugging output */\n  debug?: boolean\n  /** treat `**` the same as `*` */\n  noglobstar?: boolean\n  /** do not expand extglobs like `+(a|b)` */\n  noext?: boolean\n  /** return the pattern if nothing matches */\n  nonull?: boolean\n  /** treat `\\\\` as a path separator, not an escape character */\n  windowsPathsNoEscape?: boolean\n  /**\n   * inverse of {@link MinimatchOptions.windowsPathsNoEscape}\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n  /**\n   * Compare a partial path to a pattern. As long as the parts\n   * of the path that are present are not contradicted by the\n   * pattern, it will be treated as a match. This is useful in\n   * applications where you're walking through a folder structure,\n   * and don't yet have the full path, but want to ensure that you\n   * do not walk down paths that can never be a match.\n   */\n  partial?: boolean\n  /** allow matches that start with `.` even if the pattern does not */\n  dot?: boolean\n  /** ignore case */\n  nocase?: boolean\n  /** ignore case only in wildcard patterns */\n  nocaseMagicOnly?: boolean\n  /** consider braces to be \"magic\" for the purpose of `hasMagic` */\n  magicalBraces?: boolean\n  /**\n   * If set, then patterns without slashes will be matched\n   * against the basename of the path if it contains slashes.\n   * For example, `a?b` would match the path `/xyz/123/acb`, but\n   * not `/xyz/acb/123`.\n   */\n  matchBase?: boolean\n  /** invert the results of negated matches */\n  flipNegate?: boolean\n  /** do not collapse multiple `/` into a single `/` */\n  preserveMultipleSlashes?: boolean\n  /**\n   * A number indicating the level of optimization that should be done\n   * to the pattern prior to parsing and using it for matches.\n   */\n  optimizationLevel?: number\n  /** operating system platform */\n  platform?: Platform\n  /**\n   * When a pattern starts with a UNC path or drive letter, and in\n   * `nocase:true` mode, do not convert the root portions of the\n   * pattern into a case-insensitive regular expression, and instead\n   * leave them as strings.\n   *\n   * This is the default when the platform is `win32` and\n   * `nocase:true` is set.\n   */\n  windowsNoMagicRoot?: boolean\n  /**\n   * max number of `{...}` patterns to expand. Default 100_000.\n   */\n  braceExpandMax?: number\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n  !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) =>\n  !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n  f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) =>\n  f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) =>\n  f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process ?\n    (typeof process.env === 'object' &&\n      process.env &&\n      process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n    process.platform\n  : 'posix') as Platform\n\nexport type Sep = '\\\\' | '/'\n\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep =\n  defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed.  Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n  (pattern: string, options: MinimatchOptions = {}) =>\n  (p: string) =>\n    minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    AST: class AST extends orig.AST {\n      /* c8 ignore start */\n      constructor(\n        type: ExtglobType | null,\n        parent?: AST,\n        options: MinimatchOptions = {},\n      ) {\n        super(type, parent, ext(def, options))\n      }\n      /* c8 ignore stop */\n\n      static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n        return orig.AST.fromGlob(pattern, ext(def, options))\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) =>\n      orig.defaults(ext(def, options)),\n\n    makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.makeRe(pattern, ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (\n      list: string[],\n      pattern: string,\n      options: MinimatchOptions = {},\n    ) => orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  return expand(pattern, { max: options.braceExpandMax })\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion.  Otherwise, any series\n// of * is equivalent to a single *.  Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n  new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n  list: string[],\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n  _src?: string\n  _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n\n  regexp: false | null | MMRegExp\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    // avoid the annoying deprecation flag lol\n    const awe = ('allowWindow' + 'sEscape') as keyof MinimatchOptions\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options[awe] === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.regexp = null\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined ?\n        options.windowsNoMagicRoot\n      : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n\n    // make the set of regexps etc.\n    this.make()\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  debug(..._: any[]) {}\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.braceExpand())]\n\n    if (options.debug) {\n      this.debug = (...args: any[]) => console.error(...args)\n    }\n\n    this.debug(this.pattern, this.globSet)\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be regexps, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n    this.debug(this.pattern, this.globParts)\n\n    // glob --> regexps\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path.\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          !globMagic.test(s[3])\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [\n            ...s.slice(0, 4),\n            ...s.slice(4).map(ss => this.parse(ss)),\n          ]\n        } else if (isDrive) {\n          return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    this.debug(this.pattern, set)\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1,\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          typeof p[3] === 'string' &&\n          /^[a-z]:$/i.test(p[3])\n        ) {\n          p[2] = '?'\n        }\n      }\n    }\n\n    this.debug(this.pattern, this.set)\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn ** into *\n    if (this.options.noglobstar) {\n      for (let i = 0; i < globParts.length; i++) {\n        for (let j = 0; j < globParts[i].length; j++) {\n          if (globParts[i][j] === '**') {\n            globParts[i][j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  levelTwoFileOptimize(parts: string | string[]) {\n    if (!Array.isArray(parts)) {\n      parts = this.slashSplit(parts)\n    }\n    let didSomething: boolean = false\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes,\n        )\n        if (matched) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false,\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean = false,\n  ) {\n    const options = this.options\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi =\n        fileUNC ? 3\n        : fileDrive ? 0\n        : undefined\n      const pdi =\n        patternUNC ? 3\n        : patternDrive ? 0\n        : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          if (pdi > fdi) {\n            pattern = pattern.slice(pdi)\n          } else if (fdi > pdi) {\n            file = file.slice(fdi)\n          }\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // don't need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    this.debug('matchOne', this, { file, pattern })\n    this.debug('matchOne', file.length, pattern.length)\n\n    for (\n      var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      var p = pattern[pi]\n      var f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      // should be impossible.\n      // some invalid regexp stuff in the set.\n      /* c8 ignore start */\n      if (p === false) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      if (p === GLOBSTAR) {\n        this.debug('GLOBSTAR', [pattern, p, f])\n\n        // \"**\"\n        // a/**/b/**/c would match the following:\n        // a/b/x/y/z/c\n        // a/x/y/z/b/c\n        // a/b/x/b/x/c\n        // a/b/c\n        // To do this, take the rest of the pattern after\n        // the **, and see if it would match the file remainder.\n        // If so, return success.\n        // If not, the ** \"swallows\" a segment, and try again.\n        // This is recursively awful.\n        //\n        // a/**/b/**/c matching a/b/x/y/z/c\n        // - a matches a\n        // - doublestar\n        //   - matchOne(b/x/y/z/c, b/**/c)\n        //     - b matches b\n        //     - doublestar\n        //       - matchOne(x/y/z/c, c) -> no\n        //       - matchOne(y/z/c, c) -> no\n        //       - matchOne(z/c, c) -> no\n        //       - matchOne(c, c) yes, hit\n        var fr = fi\n        var pr = pi + 1\n        if (pr === pl) {\n          this.debug('** at the end')\n          // a ** at the end will just swallow the rest.\n          // We have found a match.\n          // however, it will not swallow /.x, unless\n          // options.dot is set.\n          // . and .. are *never* matched by **, for explosively\n          // exponential reasons.\n          for (; fi < fl; fi++) {\n            if (\n              file[fi] === '.' ||\n              file[fi] === '..' ||\n              (!options.dot && file[fi].charAt(0) === '.')\n            )\n              return false\n          }\n          return true\n        }\n\n        // ok, let's see if we can swallow whatever we can.\n        while (fr < fl) {\n          var swallowee = file[fr]\n\n          this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n          // XXX remove this slice.  Just pass the start index.\n          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n            this.debug('globstar found match!', fr, fl, swallowee)\n            // found a match.\n            return true\n          } else {\n            // can't swallow \".\" or \"..\" ever.\n            // can only swallow \".foo\" when explicitly asked.\n            if (\n              swallowee === '.' ||\n              swallowee === '..' ||\n              (!options.dot && swallowee.charAt(0) === '.')\n            ) {\n              this.debug('dot detected!', file, fr, pattern, pr)\n              break\n            }\n\n            // ** swallows a segment, and continue.\n            this.debug('globstar swallow a segment, and continue')\n            fr++\n          }\n        }\n\n        // no match was found.\n        // However, in partial mode, we can't say this is necessarily over.\n        /* c8 ignore start */\n        if (partial) {\n          // ran out of file\n          this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n          if (fr === fl) {\n            return true\n          }\n        }\n        /* c8 ignore stop */\n        return false\n      }\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into regexps.\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though \"\" matches against the\n    // [^/]*? pattern, except in partial mode, where it might\n    // simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase ?\n          options.dot ?\n            starDotExtTestNocaseDot\n          : starDotExtTestNocase\n        : options.dot ? starDotExtTestDot\n        : starDotExtTest)(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase ?\n          options.dot ?\n            qmarksTestNocaseDot\n          : qmarksTestNocase\n        : options.dot ? qmarksTestDot\n        : qmarksTest)(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar =\n      options.noglobstar ? star\n      : options.dot ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return (\n            typeof p === 'string' ? regExpEscape(p)\n            : p === GLOBSTAR ? GLOBSTAR\n            : p._src\n          )\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        const filtered = pp.filter(p => p !== GLOBSTAR)\n\n        // For partial matches, we need to make the pattern match\n        // any prefix of the full path. We do this by generating\n        // alternative patterns that match progressively longer prefixes.\n        if (this.partial && filtered.length >= 1) {\n          const prefixes: string[] = []\n          for (let i = 1; i <= filtered.length; i++) {\n            prefixes.push(filtered.slice(0, i).join('/'))\n          }\n          return '(?:' + prefixes.join('|') + ')'\n        }\n\n        return filtered.join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // In partial mode, '/' should always match as it's a valid prefix for any pattern\n    if (this.partial) {\n      re = '^(?:\\\\/|' + open + re.slice(1, -1) + close + ')$'\n    }\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch (ex) {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let i = 0; i < set.length; i++) {\n      const pattern = set[i]\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n", "import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n  FSOption,\n  Path,\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be eiher a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignored` and `childrenIgnored`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  ignore?: string | string[] | IgnoreLike\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Just passed along to Minimatch.  Note that this makes all pattern\n   * matching operations slower and *extremely* noisy.\n   */\n  debug?: boolean\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n\n  /**\n   * max number of `{...}` patterns to expand. Default `1_000`.\n   *\n   * Note: this is much less than minimatch's default of `100_000`,\n   * because Glob has higher memory requirements due to walking\n   * the file system tree.\n   */\n  braceExpandMax?: number\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[]\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    if (typeof pattern === 'string') {\n      pattern = [pattern]\n    }\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = pattern\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      braceExpandMax: 10_000,\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      // default nocase based on platform\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n      debug: !!this.opts.debug,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return [\n      ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walk()),\n    ]\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return [\n      ...new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walkSync(),\n    ]\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n", "/**\n * @module LRUCache\n */\n\n// module-private names and types\n// this provides the default Perf object source.\n// it can be passed in via configuration to override it\n// for a single LRU object.\nexport type Perf = { now: () => number }\nconst defaultPerf: Perf =\n  (\n    typeof performance === 'object' &&\n    performance &&\n    typeof performance.now === 'function'\n  ) ?\n    performance\n  : Date\n\nconst warned = new Set()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n  typeof process === 'object' && !!process ?\n    process\n  : {}) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n  msg: string,\n  type: string,\n  code: string,\n  fn: ForC,\n) => {\n  typeof PROCESS.emitWarning === 'function' ?\n    PROCESS.emitWarning(msg, type, code, fn)\n  : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n  //@ts-ignore\n  AS = class AbortSignal {\n    onabort?: (...a: any[]) => any\n    _onabort: ((...a: any[]) => any)[] = []\n    reason?: any\n    aborted: boolean = false\n    addEventListener(_: string, fn: (...a: any[]) => any) {\n      this._onabort.push(fn)\n    }\n  }\n  //@ts-ignore\n  AC = class AbortController {\n    constructor() {\n      warnACPolyfill()\n    }\n    signal = new AS()\n    abort(reason: any) {\n      if (this.signal.aborted) return\n      //@ts-ignore\n      this.signal.reason = reason\n      //@ts-ignore\n      this.signal.aborted = true\n      //@ts-ignore\n      for (const fn of this.signal._onabort) {\n        fn(reason)\n      }\n      this.signal.onabort?.(reason)\n    }\n  }\n  let printACPolyfillWarning =\n    PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n  const warnACPolyfill = () => {\n    if (!printACPolyfillWarning) return\n    printACPolyfillWarning = false\n    emitWarning(\n      'AbortController is not defined. If using lru-cache in ' +\n        'node 14, load an AbortController polyfill from the ' +\n        '`node-abort-controller` package. A minimal polyfill is ' +\n        'provided for use by LRUCache.fetch(), but it should not be ' +\n        'relied upon in other contexts (eg, passing it to other APIs that ' +\n        'use AbortController/AbortSignal might have undesirable effects). ' +\n        'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n      'NO_ABORT_CONTROLLER',\n      'ENOTSUP',\n      warnACPolyfill,\n    )\n  }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n  n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values.  Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n  !isPosInt(max) ? null\n  : max <= Math.pow(2, 8) ? Uint8Array\n  : max <= Math.pow(2, 16) ? Uint16Array\n  : max <= Math.pow(2, 32) ? Uint32Array\n  : max <= Number.MAX_SAFE_INTEGER ? ZeroArray\n  : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array {\n  constructor(size: number) {\n    super(size)\n    this.fill(0)\n  }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n  heap: NumberArray\n  length: number\n  // private constructor\n  static #constructing: boolean = false\n  static create(max: number): StackLike {\n    const HeapCls = getUintArray(max)\n    if (!HeapCls) return []\n    Stack.#constructing = true\n    const s = new Stack(max, HeapCls)\n    Stack.#constructing = false\n    return s\n  }\n  constructor(max: number, HeapCls: { new (n: number): NumberArray }) {\n    /* c8 ignore start */\n    if (!Stack.#constructing) {\n      throw new TypeError('instantiate Stack using Stack.create(n)')\n    }\n    /* c8 ignore stop */\n    this.heap = new HeapCls(max)\n    this.length = 0\n  }\n  push(n: Index) {\n    this.heap[this.length++] = n\n  }\n  pop(): Index {\n    return this.heap[--this.length] as Index\n  }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch = Promise & {\n  __returned: BackgroundFetch | undefined\n  __abortController: AbortController\n  __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask = [\n  value: V,\n  key: K,\n  reason: LRUCache.DisposeReason,\n]\n\nexport namespace LRUCache {\n  /**\n   * An integer greater than 0, reflecting the calculated size of items\n   */\n  export type Size = number\n\n  /**\n   * Integer greater than 0, representing some number of milliseconds, or the\n   * time at which a TTL started counting from.\n   */\n  export type Milliseconds = number\n\n  /**\n   * An integer greater than 0, reflecting a number of items\n   */\n  export type Count = number\n\n  /**\n   * The reason why an item was removed from the cache, passed\n   * to the {@link Disposer} methods.\n   *\n   * - `evict`: The item was evicted because it is the least recently used,\n   *   and the cache is full.\n   * - `set`: A new value was set, overwriting the old value being disposed.\n   * - `delete`: The item was explicitly deleted, either by calling\n   *   {@link LRUCache#delete}, {@link LRUCache#clear}, or\n   *   {@link LRUCache#set} with an undefined value.\n   * - `expire`: The item was removed due to exceeding its TTL.\n   * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n   *   `undefined` or was aborted, causing the item to be deleted.\n   */\n  export type DisposeReason =\n    | 'evict'\n    | 'set'\n    | 'delete'\n    | 'expire'\n    | 'fetch'\n  /**\n   * A method called upon item removal, passed as the\n   * {@link OptionsBase.dispose} and/or\n   * {@link OptionsBase.disposeAfter} options.\n   */\n  export type Disposer = (\n    value: V,\n    key: K,\n    reason: DisposeReason,\n  ) => void\n\n  /**\n   * The reason why an item was added to the cache, passed\n   * to the {@link Inserter} methods.\n   *\n   * - `add`: the item was not found in the cache, and was added\n   * - `update`: the item was in the cache, with the same value provided\n   * - `replace`: the item was in the cache, and replaced\n   */\n  export type InsertReason = 'add' | 'update' | 'replace'\n\n  /**\n   * A method called upon item insertion, passed as the\n   * {@link OptionsBase.insert}\n   */\n  export type Inserter = (\n    value: V,\n    key: K,\n    reason: InsertReason,\n  ) => void\n\n  /**\n   * A function that returns the effective calculated size\n   * of an entry in the cache.\n   */\n  export type SizeCalculator = (value: V, key: K) => Size\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.fetchMethod} function.\n   */\n  export interface FetcherOptions {\n    signal: AbortSignal\n    options: FetcherFetchOptions\n    /**\n     * Object provided in the {@link FetchOptions.context} option to\n     * {@link LRUCache#fetch}\n     */\n    context: FC\n  }\n\n  /**\n   * Occasionally, it may be useful to track the internal behavior of the\n   * cache, particularly for logging, debugging, or for behavior within the\n   * `fetchMethod`. To do this, you can pass a `status` object to the\n   * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n   * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n   *\n   * The `status` option should be a plain JavaScript object. The following\n   * fields will be set on it appropriately, depending on the situation.\n   */\n  export interface Status {\n    /**\n     * The status of a set() operation.\n     *\n     * - add: the item was not found in the cache, and was added\n     * - update: the item was in the cache, with the same value provided\n     * - replace: the item was in the cache, and replaced\n     * - miss: the item was not added to the cache for some reason\n     */\n    set?: 'add' | 'update' | 'replace' | 'miss'\n\n    /**\n     * the ttl stored for the item, or undefined if ttls are not used.\n     */\n    ttl?: Milliseconds\n\n    /**\n     * the start time for the item, or undefined if ttls are not used.\n     */\n    start?: Milliseconds\n\n    /**\n     * The timestamp used for TTL calculation\n     */\n    now?: Milliseconds\n\n    /**\n     * the remaining ttl for the item, or undefined if ttls are not used.\n     */\n    remainingTTL?: Milliseconds\n\n    /**\n     * The calculated size for the item, if sizes are used.\n     */\n    entrySize?: Size\n\n    /**\n     * The total calculated size of the cache, if sizes are used.\n     */\n    totalCalculatedSize?: Size\n\n    /**\n     * A flag indicating that the item was not stored, due to exceeding the\n     * {@link OptionsBase.maxEntrySize}\n     */\n    maxEntrySizeExceeded?: true\n\n    /**\n     * The old value, specified in the case of `set:'update'` or\n     * `set:'replace'`\n     */\n    oldValue?: V\n\n    /**\n     * The results of a {@link LRUCache#has} operation\n     *\n     * - hit: the item was found in the cache\n     * - stale: the item was found in the cache, but is stale\n     * - miss: the item was not found in the cache\n     */\n    has?: 'hit' | 'stale' | 'miss'\n\n    /**\n     * The status of a {@link LRUCache#fetch} operation.\n     * Note that this can change as the underlying fetch() moves through\n     * various states.\n     *\n     * - inflight: there is another fetch() for this key which is in process\n     * - get: there is no {@link OptionsBase.fetchMethod}, so\n     *   {@link LRUCache#get} was called.\n     * - miss: the item is not in cache, and will be fetched.\n     * - hit: the item is in the cache, and was resolved immediately.\n     * - stale: the item is in the cache, but stale.\n     * - refresh: the item is in the cache, and not stale, but\n     *   {@link FetchOptions.forceRefresh} was specified.\n     */\n    fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n    /**\n     * The {@link OptionsBase.fetchMethod} was called\n     */\n    fetchDispatched?: true\n\n    /**\n     * The cached value was updated after a successful call to\n     * {@link OptionsBase.fetchMethod}\n     */\n    fetchUpdated?: true\n\n    /**\n     * The reason for a fetch() rejection.  Either the error raised by the\n     * {@link OptionsBase.fetchMethod}, or the reason for an\n     * AbortSignal.\n     */\n    fetchError?: Error\n\n    /**\n     * The fetch received an abort signal\n     */\n    fetchAborted?: true\n\n    /**\n     * The abort signal received was ignored, and the fetch was allowed to\n     * continue.\n     */\n    fetchAbortIgnored?: true\n\n    /**\n     * The fetchMethod promise resolved successfully\n     */\n    fetchResolved?: true\n\n    /**\n     * The fetchMethod promise was rejected\n     */\n    fetchRejected?: true\n\n    /**\n     * The status of a {@link LRUCache#get} operation.\n     *\n     * - fetching: The item is currently being fetched.  If a previous value\n     *   is present and allowed, that will be returned.\n     * - stale: The item is in the cache, and is stale.\n     * - hit: the item is in the cache\n     * - miss: the item is not in the cache\n     */\n    get?: 'stale' | 'hit' | 'miss'\n\n    /**\n     * A fetch or get operation returned a stale value.\n     */\n    returnedStale?: true\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#fetch}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link OptionsBase.noDeleteOnFetchRejection},\n   * {@link OptionsBase.allowStaleOnFetchRejection},\n   * {@link FetchOptions.forceRefresh}, and\n   * {@link FetcherOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the fetchMethod is called.\n   */\n  export interface FetcherFetchOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n      | 'noDeleteOnFetchRejection'\n      | 'allowStaleOnFetchRejection'\n      | 'ignoreFetchAbort'\n      | 'allowStaleOnFetchAbort'\n    > {\n    status?: Status\n    size?: Size\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#fetch} method.\n   */\n  export interface FetchOptions\n    extends FetcherFetchOptions {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.fetchMethod} as\n     * the {@link FetcherOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    signal?: AbortSignal\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface FetchOptionsWithContext\n    extends FetchOptions {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface FetchOptionsNoContext\n    extends FetchOptions {\n    context?: undefined\n  }\n\n  export interface MemoOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n      | 'noDeleteOnFetchRejection'\n      | 'allowStaleOnFetchRejection'\n      | 'ignoreFetchAbort'\n      | 'allowStaleOnFetchAbort'\n    > {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.memoMethod} as\n     * the {@link MemoizerOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface MemoOptionsWithContext\n    extends MemoOptions {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface MemoOptionsNoContext\n    extends MemoOptions {\n    context?: undefined\n  }\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.memoMethod} function.\n   */\n  export interface MemoizerOptions {\n    options: MemoizerMemoOptions\n    /**\n     * Object provided in the {@link MemoOptions.context} option to\n     * {@link LRUCache#memo}\n     */\n    context: FC\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#memo}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link MemoOptions.forceRefresh}, and\n   * {@link MemoOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.memoMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the memoMethod is called.\n   */\n  export interface MemoizerMemoOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n    > {\n    status?: Status\n    size?: Size\n    start?: Milliseconds\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#has} method.\n   */\n  export interface HasOptions\n    extends Pick, 'updateAgeOnHas'> {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#get} method.\n   */\n  export interface GetOptions\n    extends Pick<\n      OptionsBase,\n      'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n    > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#peek} method.\n   */\n  export interface PeekOptions\n    extends Pick, 'allowStale'> {}\n\n  /**\n   * Options that may be passed to the {@link LRUCache#set} method.\n   */\n  export interface SetOptions\n    extends Pick<\n      OptionsBase,\n      'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n    > {\n    /**\n     * If size tracking is enabled, then setting an explicit size\n     * in the {@link LRUCache#set} call will prevent calling the\n     * {@link OptionsBase.sizeCalculation} function.\n     */\n    size?: Size\n    /**\n     * If TTL tracking is enabled, then setting an explicit start\n     * time in the {@link LRUCache#set} call will override the\n     * default time from `performance.now()` or `Date.now()`.\n     *\n     * Note that it must be a valid value for whichever time-tracking\n     * method is in use.\n     */\n    start?: Milliseconds\n    status?: Status\n  }\n\n  /**\n   * The type signature for the {@link OptionsBase.fetchMethod} option.\n   */\n  export type Fetcher = (\n    key: K,\n    staleValue: V | undefined,\n    options: FetcherOptions,\n  ) => Promise | V | undefined | void\n\n  /**\n   * the type signature for the {@link OptionsBase.memoMethod} option.\n   */\n  export type Memoizer = (\n    key: K,\n    staleValue: V | undefined,\n    options: MemoizerOptions,\n  ) => V\n\n  /**\n   * Options which may be passed to the {@link LRUCache} constructor.\n   *\n   * Most of these may be overridden in the various options that use\n   * them.\n   *\n   * Despite all being technically optional, the constructor requires that\n   * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n   * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n   *\n   * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n   * (and in fact required by the type definitions here) that the cache\n   * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n   * unbounded storage.\n   *\n   * All options are also available on the {@link LRUCache} instance, making\n   * it safe to pass an LRUCache instance as the options argumemnt to\n   * make another empty cache of the same type.\n   *\n   * Some options are marked as read-only, because changing them after\n   * instantiation is not safe. Changing any of the other options will of\n   * course only have an effect on subsequent method calls.\n   */\n  export interface OptionsBase {\n    /**\n     * The maximum number of items to store in the cache before evicting\n     * old entries. This is read-only on the {@link LRUCache} instance,\n     * and may not be overridden.\n     *\n     * If set, then storage space will be pre-allocated at construction\n     * time, and the cache will perform significantly faster.\n     *\n     * Note that significantly fewer items may be stored, if\n     * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n     * set.\n     *\n     * **It is strongly recommended to set a `max` to prevent unbounded growth\n     * of the cache.**\n     */\n    max?: Count\n\n    /**\n     * Max time in milliseconds for items to live in cache before they are\n     * considered stale.  Note that stale items are NOT preemptively removed by\n     * default, and MAY live in the cache, contributing to its LRU max, long\n     * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n     * set.\n     *\n     * If set to `0` (the default value), then that means \"do not track\n     * TTL\", not \"expire immediately\".\n     *\n     * Also, as this cache is optimized for LRU/MRU operations, some of\n     * the staleness/TTL checks will reduce performance, as they will incur\n     * overhead by deleting items.\n     *\n     * This is not primarily a TTL cache, and does not make strong TTL\n     * guarantees. There is no pre-emptive pruning of expired items, but you\n     * _may_ set a TTL on the cache, and it will treat expired items as missing\n     * when they are fetched, and delete them.\n     *\n     * Optional, but must be a non-negative integer in ms if specified.\n     *\n     * This may be overridden by passing an options object to `cache.set()`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if ttl tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n     * and `ttlAutopurge` is not set, then a warning will be emitted\n     * cautioning about the potential for unbounded memory consumption.\n     * (The TypeScript definitions will also discourage this.)\n     */\n    ttl?: Milliseconds\n\n    /**\n     * Minimum amount of time in ms in which to check for staleness.\n     * Defaults to 1, which means that the current time is checked\n     * at most once per millisecond.\n     *\n     * Set to 0 to check the current time every time staleness is tested.\n     * (This reduces performance, and is theoretically unnecessary.)\n     *\n     * Setting this to a higher value will improve performance somewhat\n     * while using ttl tracking, albeit at the expense of keeping stale\n     * items around a bit longer than their TTLs would indicate.\n     *\n     * @default 1\n     */\n    ttlResolution?: Milliseconds\n\n    /**\n     * Preemptively remove stale items from the cache.\n     *\n     * Note that this may *significantly* degrade performance, especially if\n     * the cache is storing a large number of items. It is almost always best\n     * to just leave the stale items in the cache, and let them fall out as new\n     * items are added.\n     *\n     * Note that this means that {@link OptionsBase.allowStale} is a bit\n     * pointless, as stale items will be deleted almost as soon as they\n     * expire.\n     *\n     * Use with caution!\n     */\n    ttlAutopurge?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever it is retrieved from cache with\n     * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n     * of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     */\n    updateAgeOnGet?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever its presence in the cache is\n     * checked with {@link LRUCache#has}, causing it to not expire. (It can\n     * still fall out of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     */\n    updateAgeOnHas?: boolean\n\n    /**\n     * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n     * stale data, if available.\n     *\n     * By default, if you set `ttl`, stale items will only be deleted from the\n     * cache when you `get(key)`. That is, it's not preemptively pruning items,\n     * unless {@link OptionsBase.ttlAutopurge} is set.\n     *\n     * If you set `allowStale:true`, it'll return the stale value *as well as*\n     * deleting it. If you don't set this, then it'll return `undefined` when\n     * you try to get a stale entry.\n     *\n     * Note that when a stale entry is fetched, _even if it is returned due to\n     * `allowStale` being set_, it is removed from the cache immediately. You\n     * can suppress this behavior by setting\n     * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n     * the options provided to {@link LRUCache#get}.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     * The `cache.has()` method will always return `false` for stale items.\n     *\n     * Only relevant if a ttl is set.\n     */\n    allowStale?: boolean\n\n    /**\n     * Function that is called on items when they are dropped from the\n     * cache, as `dispose(value, key, reason)`.\n     *\n     * This can be handy if you want to close file descriptors or do\n     * other cleanup tasks when items are no longer stored in the cache.\n     *\n     * **NOTE**: It is called _before_ the item has been fully removed\n     * from the cache, so if you want to put it right back in, you need\n     * to wait until the next tick. If you try to add it back in during\n     * the `dispose()` function call, it will break things in subtle and\n     * weird ways.\n     *\n     * Unlike several other options, this may _not_ be overridden by\n     * passing an option to `set()`, for performance reasons.\n     *\n     * The `reason` will be one of the following strings, corresponding\n     * to the reason for the item's deletion:\n     *\n     * - `evict` Item was evicted to make space for a new addition\n     * - `set` Item was overwritten by a new value\n     * - `expire` Item expired its TTL\n     * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n     *   fetchMethod returning `undefined.\n     * - `delete` Item was removed by explicit `cache.delete(key)`,\n     *   `cache.clear()`, or `cache.set(key, undefined)`.\n     */\n    dispose?: Disposer\n\n    /**\n     * Function that is called when new items are inserted into the cache,\n     * as `onInsert(value, key, reason)`.\n     *\n     * This can be useful if you need to perform actions when an item is\n     * added, such as logging or tracking insertions.\n     *\n     * Unlike some other options, this may _not_ be overridden by passing\n     * an option to `set()`, for performance and consistency reasons.\n     */\n    onInsert?: Inserter\n\n    /**\n     * The same as {@link OptionsBase.dispose}, but called *after* the entry\n     * is completely removed and the cache is once again in a clean state.\n     *\n     * It is safe to add an item right back into the cache at this point.\n     * However, note that it is *very* easy to inadvertently create infinite\n     * recursion this way.\n     */\n    disposeAfter?: Disposer\n\n    /**\n     * Set to true to suppress calling the\n     * {@link OptionsBase.dispose} function if the entry key is\n     * still accessible within the cache.\n     *\n     * This may be overridden by passing an options object to\n     * {@link LRUCache#set}.\n     *\n     * Only relevant if `dispose` or `disposeAfter` are set.\n     */\n    noDisposeOnSet?: boolean\n\n    /**\n     * Boolean flag to tell the cache to not update the TTL when setting a new\n     * value for an existing key (ie, when updating a value rather than\n     * inserting a new value).  Note that the TTL value is _always_ set (if\n     * provided) when adding a new entry into the cache.\n     *\n     * Has no effect if a {@link OptionsBase.ttl} is not set.\n     *\n     * May be passed as an option to {@link LRUCache#set}.\n     */\n    noUpdateTTL?: boolean\n\n    /**\n     * Set to a positive integer to track the sizes of items added to the\n     * cache, and automatically evict items in order to stay below this size.\n     * Note that this may result in fewer than `max` items being stored.\n     *\n     * Attempting to add an item to the cache whose calculated size is greater\n     * that this amount will be a no-op. The item will not be cached, and no\n     * other items will be evicted.\n     *\n     * Optional, must be a positive integer if provided.\n     *\n     * Sets `maxEntrySize` to the same value, unless a different value is\n     * provided for `maxEntrySize`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if size tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * Note also that size tracking can negatively impact performance,\n     * though for most cases, only minimally.\n     */\n    maxSize?: Size\n\n    /**\n     * The maximum allowed size for any single item in the cache.\n     *\n     * If a larger item is passed to {@link LRUCache#set} or returned by a\n     * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n     * it will not be stored in the cache.\n     *\n     * Attempting to add an item whose calculated size is greater than\n     * this amount will not cache the item or evict any old items, but\n     * WILL delete an existing value if one is already present.\n     *\n     * Optional, must be a positive integer if provided. Defaults to\n     * the value of `maxSize` if provided.\n     */\n    maxEntrySize?: Size\n\n    /**\n     * A function that returns a number indicating the item's size.\n     *\n     * Requires {@link OptionsBase.maxSize} to be set.\n     *\n     * If not provided, and {@link OptionsBase.maxSize} or\n     * {@link OptionsBase.maxEntrySize} are set, then all\n     * {@link LRUCache#set} calls **must** provide an explicit\n     * {@link SetOptions.size} or sizeCalculation param.\n     */\n    sizeCalculation?: SizeCalculator\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#fetch}\n     *\n     * ```ts\n     * fetchMethod(key, staleValue, { signal, options, context })\n     * ```\n     *\n     * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n     * to `Promise.resolve(cache.get(key))`.\n     *\n     * If at any time, `signal.aborted` is set to `true`, or if the\n     * `signal.onabort` method is called, or if it emits an `'abort'` event\n     * which you can listen to with `addEventListener`, then that means that\n     * the fetch should be abandoned. This may be passed along to async\n     * functions aware of AbortController/AbortSignal behavior.\n     *\n     * The `fetchMethod` should **only** return `undefined` or a Promise\n     * resolving to `undefined` if the AbortController signaled an `abort`\n     * event. In all other cases, it should return or resolve to a value\n     * suitable for adding to the cache.\n     *\n     * The `options` object is a union of the options that may be provided to\n     * `set()` and `get()`. If they are modified, then that will result in\n     * modifying the settings to `cache.set()` when the value is resolved, and\n     * in the case of\n     * {@link OptionsBase.noDeleteOnFetchRejection} and\n     * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n     * `fetchMethod` failures.\n     *\n     * For example, a DNS cache may update the TTL based on the value returned\n     * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n     */\n    fetchMethod?: Fetcher\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#memo}\n     */\n    memoMethod?: Memoizer\n\n    /**\n     * Set to true to suppress the deletion of stale data when a\n     * {@link OptionsBase.fetchMethod} returns a rejected promise.\n     */\n    noDeleteOnFetchRejection?: boolean\n\n    /**\n     * Do not delete stale items when they are retrieved with\n     * {@link LRUCache#get}.\n     *\n     * Note that the `get` return value will still be `undefined`\n     * unless {@link OptionsBase.allowStale} is true.\n     *\n     * When using time-expiring entries with `ttl`, by default stale\n     * items will be removed from the cache when the key is accessed\n     * with `cache.get()`.\n     *\n     * Setting this option will cause stale items to remain in the cache, until\n     * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n     * `noDeleteOnStaleGet` set to `false`.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     *\n     * Only relevant if a ttl is used.\n     */\n    noDeleteOnStaleGet?: boolean\n\n    /**\n     * Set to true to allow returning stale data when a\n     * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n     * promise.\n     *\n     * This differs from using {@link OptionsBase.allowStale} in that stale\n     * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n     * fails, not any other times.\n     *\n     * If a `fetchMethod` fails, and there is no stale value available, the\n     * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n     * suppressed.\n     *\n     * Implies `noDeleteOnFetchRejection`.\n     *\n     * This may be set in calls to `fetch()`, or defaulted on the constructor,\n     * or overridden by modifying the options object in the `fetchMethod`.\n     */\n    allowStaleOnFetchRejection?: boolean\n\n    /**\n     * Set to true to return a stale value from the cache when the\n     * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n     * an `'abort'` event, whether user-triggered, or due to internal cache\n     * behavior.\n     *\n     * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n     * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n     * any value it returns will be ignored and not cached.\n     *\n     * Caveat: since fetches are aborted when a new value is explicitly\n     * set in the cache, this can lead to fetch returning a stale value,\n     * since that was the fallback value _at the moment the `fetch()` was\n     * initiated_, even though the new updated value is now present in\n     * the cache.\n     *\n     * For example:\n     *\n     * ```ts\n     * const cache = new LRUCache({\n     *   ttl: 100,\n     *   fetchMethod: async (url, oldValue, { signal }) =>  {\n     *     const res = await fetch(url, { signal })\n     *     return await res.json()\n     *   }\n     * })\n     * cache.set('https://example.com/', { some: 'data' })\n     * // 100ms go by...\n     * const result = cache.fetch('https://example.com/')\n     * cache.set('https://example.com/', { other: 'thing' })\n     * console.log(await result) // { some: 'data' }\n     * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n     * ```\n     */\n    allowStaleOnFetchAbort?: boolean\n\n    /**\n     * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n     * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n     * resulting resolution value, as long as it is not `undefined`.\n     *\n     * When used on its own, this means aborted {@link LRUCache#fetch} calls\n     * are not immediately resolved or rejected when they are aborted, and\n     * instead take the full time to await.\n     *\n     * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n     * {@link LRUCache#fetch} calls will resolve immediately to their stale\n     * cached value or `undefined`, and will continue to process and eventually\n     * update the cache when they resolve, as long as the resulting value is\n     * not `undefined`, thus supporting a \"return stale on timeout while\n     * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n     *\n     * For example:\n     *\n     * ```ts\n     * const c = new LRUCache({\n     *   ttl: 100,\n     *   ignoreFetchAbort: true,\n     *   allowStaleOnFetchAbort: true,\n     *   fetchMethod: async (key, oldValue, { signal }) => {\n     *     // note: do NOT pass the signal to fetch()!\n     *     // let's say this fetch can take a long time.\n     *     const res = await fetch(`https://slow-backend-server/${key}`)\n     *     return await res.json()\n     *   },\n     * })\n     *\n     * // this will return the stale value after 100ms, while still\n     * // updating in the background for next time.\n     * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n     * ```\n     *\n     * **Note**: regardless of this setting, an `abort` event _is still\n     * emitted on the `AbortSignal` object_, so may result in invalid results\n     * when passed to other underlying APIs that use AbortSignals.\n     *\n     * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n     * call to {@link LRUCache#fetch}.\n     */\n    ignoreFetchAbort?: boolean\n\n    /**\n     * In some cases, you may want to swap out the performance/Date object\n     * used for TTL tracking. This should almost certainly NOT be done in\n     * production environments!\n     *\n     * This value defaults to `global.performance` if it has a `now()` method,\n     * or the `global.Date` object otherwise.\n     */\n    perf?: Perf\n  }\n\n  export interface OptionsMaxLimit\n    extends OptionsBase {\n    max: Count\n  }\n  export interface OptionsTTLLimit\n    extends OptionsBase {\n    ttl: Milliseconds\n    ttlAutopurge: boolean\n  }\n  export interface OptionsSizeLimit\n    extends OptionsBase {\n    maxSize: Size\n  }\n\n  /**\n   * The valid safe options for the {@link LRUCache} constructor\n   */\n  export type Options =\n    | OptionsMaxLimit\n    | OptionsSizeLimit\n    | OptionsTTLLimit\n\n  /**\n   * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n   * and returned by {@link LRUCache#info}.\n   */\n  export interface Entry {\n    value: V\n    ttl?: Milliseconds\n    size?: Size\n    start?: Milliseconds\n  }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache {\n  // options that cannot be changed without disaster\n  readonly #max: LRUCache.Count\n  readonly #maxSize: LRUCache.Size\n  readonly #dispose?: LRUCache.Disposer\n  readonly #onInsert?: LRUCache.Inserter\n  readonly #disposeAfter?: LRUCache.Disposer\n  readonly #fetchMethod?: LRUCache.Fetcher\n  readonly #memoMethod?: LRUCache.Memoizer\n  readonly #perf: Perf\n\n  /**\n   * {@link LRUCache.OptionsBase.perf}\n   */\n  get perf() {\n    return this.#perf\n  }\n\n  /**\n   * {@link LRUCache.OptionsBase.ttl}\n   */\n  ttl: LRUCache.Milliseconds\n\n  /**\n   * {@link LRUCache.OptionsBase.ttlResolution}\n   */\n  ttlResolution: LRUCache.Milliseconds\n  /**\n   * {@link LRUCache.OptionsBase.ttlAutopurge}\n   */\n  ttlAutopurge: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnGet}\n   */\n  updateAgeOnGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnHas}\n   */\n  updateAgeOnHas: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStale}\n   */\n  allowStale: boolean\n\n  /**\n   * {@link LRUCache.OptionsBase.noDisposeOnSet}\n   */\n  noDisposeOnSet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noUpdateTTL}\n   */\n  noUpdateTTL: boolean\n  /**\n   * {@link LRUCache.OptionsBase.maxEntrySize}\n   */\n  maxEntrySize: LRUCache.Size\n  /**\n   * {@link LRUCache.OptionsBase.sizeCalculation}\n   */\n  sizeCalculation?: LRUCache.SizeCalculator\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n   */\n  noDeleteOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n   */\n  noDeleteOnStaleGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n   */\n  allowStaleOnFetchAbort: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n   */\n  allowStaleOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n   */\n  ignoreFetchAbort: boolean\n\n  // computed properties\n  #size: LRUCache.Count\n  #calculatedSize: LRUCache.Size\n  #keyMap: Map\n  #keyList: (K | undefined)[]\n  #valList: (V | BackgroundFetch | undefined)[]\n  #next: NumberArray\n  #prev: NumberArray\n  #head: Index\n  #tail: Index\n  #free: StackLike\n  #disposed?: DisposeTask[]\n  #sizes?: ZeroArray\n  #starts?: ZeroArray\n  #ttls?: ZeroArray\n  #autopurgeTimers?: (undefined | ReturnType)[]\n\n  #hasDispose: boolean\n  #hasFetchMethod: boolean\n  #hasDisposeAfter: boolean\n  #hasOnInsert: boolean\n\n  /**\n   * Do not call this method unless you need to inspect the\n   * inner workings of the cache.  If anything returned by this\n   * object is modified in any way, strange breakage may occur.\n   *\n   * These fields are private for a reason!\n   *\n   * @internal\n   */\n  static unsafeExposeInternals<\n    K extends {},\n    V extends {},\n    FC extends unknown = unknown,\n  >(c: LRUCache) {\n    return {\n      // properties\n      starts: c.#starts,\n      ttls: c.#ttls,\n      autopurgeTimers: c.#autopurgeTimers,\n      sizes: c.#sizes,\n      keyMap: c.#keyMap as Map,\n      keyList: c.#keyList,\n      valList: c.#valList,\n      next: c.#next,\n      prev: c.#prev,\n      get head() {\n        return c.#head\n      },\n      get tail() {\n        return c.#tail\n      },\n      free: c.#free,\n      // methods\n      isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n      backgroundFetch: (\n        k: K,\n        index: number | undefined,\n        options: LRUCache.FetchOptions,\n        context: any,\n      ): BackgroundFetch =>\n        c.#backgroundFetch(\n          k,\n          index as Index | undefined,\n          options,\n          context,\n        ),\n      moveToTail: (index: number): void => c.#moveToTail(index as Index),\n      indexes: (options?: { allowStale: boolean }) => c.#indexes(options),\n      rindexes: (options?: { allowStale: boolean }) =>\n        c.#rindexes(options),\n      isStale: (index: number | undefined) => c.#isStale(index as Index),\n    }\n  }\n\n  // Protected read-only members\n\n  /**\n   * {@link LRUCache.OptionsBase.max} (read-only)\n   */\n  get max(): LRUCache.Count {\n    return this.#max\n  }\n  /**\n   * {@link LRUCache.OptionsBase.maxSize} (read-only)\n   */\n  get maxSize(): LRUCache.Count {\n    return this.#maxSize\n  }\n  /**\n   * The total computed size of items in the cache (read-only)\n   */\n  get calculatedSize(): LRUCache.Size {\n    return this.#calculatedSize\n  }\n  /**\n   * The number of items stored in the cache (read-only)\n   */\n  get size(): LRUCache.Count {\n    return this.#size\n  }\n  /**\n   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n   */\n  get fetchMethod(): LRUCache.Fetcher | undefined {\n    return this.#fetchMethod\n  }\n  get memoMethod(): LRUCache.Memoizer | undefined {\n    return this.#memoMethod\n  }\n  /**\n   * {@link LRUCache.OptionsBase.dispose} (read-only)\n   */\n  get dispose() {\n    return this.#dispose\n  }\n  /**\n   * {@link LRUCache.OptionsBase.onInsert} (read-only)\n   */\n  get onInsert() {\n    return this.#onInsert\n  }\n  /**\n   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n   */\n  get disposeAfter() {\n    return this.#disposeAfter\n  }\n\n  constructor(options: LRUCache.Options | LRUCache) {\n    const {\n      max = 0,\n      ttl,\n      ttlResolution = 1,\n      ttlAutopurge,\n      updateAgeOnGet,\n      updateAgeOnHas,\n      allowStale,\n      dispose,\n      onInsert,\n      disposeAfter,\n      noDisposeOnSet,\n      noUpdateTTL,\n      maxSize = 0,\n      maxEntrySize = 0,\n      sizeCalculation,\n      fetchMethod,\n      memoMethod,\n      noDeleteOnFetchRejection,\n      noDeleteOnStaleGet,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      perf,\n    } = options\n\n    if (perf !== undefined) {\n      if (typeof perf?.now !== 'function') {\n        throw new TypeError(\n          'perf option must have a now() method if specified',\n        )\n      }\n    }\n\n    this.#perf = perf ?? defaultPerf\n\n    if (max !== 0 && !isPosInt(max)) {\n      throw new TypeError('max option must be a nonnegative integer')\n    }\n\n    const UintArray = max ? getUintArray(max) : Array\n    if (!UintArray) {\n      throw new Error('invalid max value: ' + max)\n    }\n\n    this.#max = max\n    this.#maxSize = maxSize\n    this.maxEntrySize = maxEntrySize || this.#maxSize\n    this.sizeCalculation = sizeCalculation\n    if (this.sizeCalculation) {\n      if (!this.#maxSize && !this.maxEntrySize) {\n        throw new TypeError(\n          'cannot set sizeCalculation without setting maxSize or maxEntrySize',\n        )\n      }\n      if (typeof this.sizeCalculation !== 'function') {\n        throw new TypeError('sizeCalculation set to non-function')\n      }\n    }\n\n    if (memoMethod !== undefined && typeof memoMethod !== 'function') {\n      throw new TypeError('memoMethod must be a function if defined')\n    }\n    this.#memoMethod = memoMethod\n\n    if (fetchMethod !== undefined && typeof fetchMethod !== 'function') {\n      throw new TypeError('fetchMethod must be a function if specified')\n    }\n    this.#fetchMethod = fetchMethod\n    this.#hasFetchMethod = !!fetchMethod\n\n    this.#keyMap = new Map()\n    this.#keyList = new Array(max).fill(undefined)\n    this.#valList = new Array(max).fill(undefined)\n    this.#next = new UintArray(max)\n    this.#prev = new UintArray(max)\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free = Stack.create(max)\n    this.#size = 0\n    this.#calculatedSize = 0\n\n    if (typeof dispose === 'function') {\n      this.#dispose = dispose\n    }\n    if (typeof onInsert === 'function') {\n      this.#onInsert = onInsert\n    }\n    if (typeof disposeAfter === 'function') {\n      this.#disposeAfter = disposeAfter\n      this.#disposed = []\n    } else {\n      this.#disposeAfter = undefined\n      this.#disposed = undefined\n    }\n    this.#hasDispose = !!this.#dispose\n    this.#hasOnInsert = !!this.#onInsert\n    this.#hasDisposeAfter = !!this.#disposeAfter\n\n    this.noDisposeOnSet = !!noDisposeOnSet\n    this.noUpdateTTL = !!noUpdateTTL\n    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n    this.ignoreFetchAbort = !!ignoreFetchAbort\n\n    // NB: maxEntrySize is set to maxSize if it's set\n    if (this.maxEntrySize !== 0) {\n      if (this.#maxSize !== 0) {\n        if (!isPosInt(this.#maxSize)) {\n          throw new TypeError(\n            'maxSize must be a positive integer if specified',\n          )\n        }\n      }\n      if (!isPosInt(this.maxEntrySize)) {\n        throw new TypeError(\n          'maxEntrySize must be a positive integer if specified',\n        )\n      }\n      this.#initializeSizeTracking()\n    }\n\n    this.allowStale = !!allowStale\n    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n    this.updateAgeOnGet = !!updateAgeOnGet\n    this.updateAgeOnHas = !!updateAgeOnHas\n    this.ttlResolution =\n      isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1\n    this.ttlAutopurge = !!ttlAutopurge\n    this.ttl = ttl || 0\n    if (this.ttl) {\n      if (!isPosInt(this.ttl)) {\n        throw new TypeError('ttl must be a positive integer if specified')\n      }\n      this.#initializeTTLTracking()\n    }\n\n    // do not allow completely unbounded caches\n    if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n      throw new TypeError(\n        'At least one of max, maxSize, or ttl is required',\n      )\n    }\n    if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n      const code = 'LRU_CACHE_UNBOUNDED'\n      if (shouldWarn(code)) {\n        warned.add(code)\n        const msg =\n          'TTL caching without ttlAutopurge, max, or maxSize can ' +\n          'result in unbounded memory consumption.'\n        emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n      }\n    }\n  }\n\n  /**\n   * Return the number of ms left in the item's TTL. If item is not in cache,\n   * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n   */\n  getRemainingTTL(key: K) {\n    return this.#keyMap.has(key) ? Infinity : 0\n  }\n\n  #initializeTTLTracking() {\n    const ttls = new ZeroArray(this.#max)\n    const starts = new ZeroArray(this.#max)\n    this.#ttls = ttls\n    this.#starts = starts\n    const purgeTimers =\n      this.ttlAutopurge ?\n        new Array>(this.#max)\n      : undefined\n    this.#autopurgeTimers = purgeTimers\n\n    this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {\n      starts[index] = ttl !== 0 ? start : 0\n      ttls[index] = ttl\n      // clear out the purge timer if we're setting TTL to 0, and\n      // previously had a ttl purge timer running, so it doesn't\n      // fire unnecessarily.\n      if (purgeTimers?.[index]) {\n        clearTimeout(purgeTimers[index])\n        purgeTimers[index] = undefined\n      }\n      if (ttl !== 0 && purgeTimers) {\n        const t = setTimeout(() => {\n          if (this.#isStale(index)) {\n            this.#delete(this.#keyList[index] as K, 'expire')\n          }\n        }, ttl + 1)\n        // unref() not supported on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n        purgeTimers[index] = t\n      }\n    }\n\n    this.#updateItemAge = index => {\n      starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0\n    }\n\n    this.#statusTTL = (status, index) => {\n      if (ttls[index]) {\n        const ttl = ttls[index]\n        const start = starts[index]\n        /* c8 ignore next */\n        if (!ttl || !start) return\n        status.ttl = ttl\n        status.start = start\n        status.now = cachedNow || getNow()\n        const age = status.now - start\n        status.remainingTTL = ttl - age\n      }\n    }\n\n    // debounce calls to perf.now() to 1s so we're not hitting\n    // that costly call repeatedly.\n    let cachedNow = 0\n    const getNow = () => {\n      const n = this.#perf.now()\n      if (this.ttlResolution > 0) {\n        cachedNow = n\n        const t = setTimeout(() => (cachedNow = 0), this.ttlResolution)\n        // not available on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n      return n\n    }\n\n    this.getRemainingTTL = key => {\n      const index = this.#keyMap.get(key)\n      if (index === undefined) {\n        return 0\n      }\n      const ttl = ttls[index]\n      const start = starts[index]\n      if (!ttl || !start) {\n        return Infinity\n      }\n      const age = (cachedNow || getNow()) - start\n      return ttl - age\n    }\n\n    this.#isStale = index => {\n      const s = starts[index]\n      const t = ttls[index]\n      return !!t && !!s && (cachedNow || getNow()) - s > t\n    }\n  }\n\n  // conditionally set private methods related to TTL\n  #updateItemAge: (index: Index) => void = () => {}\n  #statusTTL: (status: LRUCache.Status, index: Index) => void = () => {}\n  #setItemTTL: (\n    index: Index,\n    ttl: LRUCache.Milliseconds,\n    start?: LRUCache.Milliseconds,\n    // ignore because we never call this if we're not already in TTL mode\n    /* c8 ignore start */\n  ) => void = () => {}\n  /* c8 ignore stop */\n\n  #isStale: (index: Index) => boolean = () => false\n\n  #initializeSizeTracking() {\n    const sizes = new ZeroArray(this.#max)\n    this.#calculatedSize = 0\n    this.#sizes = sizes\n    this.#removeItemSize = index => {\n      this.#calculatedSize -= sizes[index] as number\n      sizes[index] = 0\n    }\n    this.#requireSize = (k, v, size, sizeCalculation) => {\n      // provisionally accept background fetches.\n      // actual value size will be checked when they return.\n      if (this.#isBackgroundFetch(v)) {\n        return 0\n      }\n      if (!isPosInt(size)) {\n        if (sizeCalculation) {\n          if (typeof sizeCalculation !== 'function') {\n            throw new TypeError('sizeCalculation must be a function')\n          }\n          size = sizeCalculation(v, k)\n          if (!isPosInt(size)) {\n            throw new TypeError(\n              'sizeCalculation return invalid (expect positive integer)',\n            )\n          }\n        } else {\n          throw new TypeError(\n            'invalid size value (must be positive integer). ' +\n              'When maxSize or maxEntrySize is used, sizeCalculation ' +\n              'or size must be set.',\n          )\n        }\n      }\n      return size\n    }\n    this.#addItemSize = (\n      index: Index,\n      size: LRUCache.Size,\n      status?: LRUCache.Status,\n    ) => {\n      sizes[index] = size\n      if (this.#maxSize) {\n        const maxSize = this.#maxSize - (sizes[index] as number)\n        while (this.#calculatedSize > maxSize) {\n          this.#evict(true)\n        }\n      }\n      this.#calculatedSize += sizes[index] as number\n      if (status) {\n        status.entrySize = size\n        status.totalCalculatedSize = this.#calculatedSize\n      }\n    }\n  }\n\n  #removeItemSize: (index: Index) => void = _i => {}\n  #addItemSize: (\n    index: Index,\n    size: LRUCache.Size,\n    status?: LRUCache.Status,\n  ) => void = (_i, _s, _st) => {}\n  #requireSize: (\n    k: K,\n    v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator,\n  ) => LRUCache.Size = (\n    _k: K,\n    _v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator,\n  ) => {\n    if (size || sizeCalculation) {\n      throw new TypeError(\n        'cannot set size without setting maxSize or maxEntrySize on cache',\n      )\n    }\n    return 0\n  };\n\n  *#indexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#tail; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#head) {\n          break\n        } else {\n          i = this.#prev[i] as Index\n        }\n      }\n    }\n  }\n\n  *#rindexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#head; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#tail) {\n          break\n        } else {\n          i = this.#next[i] as Index\n        }\n      }\n    }\n  }\n\n  #isValidIndex(index: Index) {\n    return (\n      index !== undefined &&\n      this.#keyMap.get(this.#keyList[index] as K) === index\n    )\n  }\n\n  /**\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from most recently used to least recently used.\n   */\n  *entries() {\n    for (const i of this.#indexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]] as [K, V]\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.entries}\n   *\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from least recently used to most recently used.\n   */\n  *rentries() {\n    for (const i of this.#rindexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]]\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the keys in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *keys() {\n    for (const i of this.#indexes()) {\n      const k = this.#keyList[i]\n      if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.keys}\n   *\n   * Return a generator yielding the keys in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rkeys() {\n    for (const i of this.#rindexes()) {\n      const k = this.#keyList[i]\n      if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the values in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *values() {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield this.#valList[i] as V\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.values}\n   *\n   * Return a generator yielding the values in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rvalues() {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield this.#valList[i]\n      }\n    }\n  }\n\n  /**\n   * Iterating over the cache itself yields the same results as\n   * {@link LRUCache.entries}\n   */\n  [Symbol.iterator]() {\n    return this.entries()\n  }\n\n  /**\n   * A String value that is used in the creation of the default string\n   * description of an object. Called by the built-in method\n   * `Object.prototype.toString`.\n   */\n  [Symbol.toStringTag] = 'LRUCache'\n\n  /**\n   * Find a value for which the supplied fn method returns a truthy value,\n   * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n   */\n  find(\n    fn: (v: V, k: K, self: LRUCache) => boolean,\n    getOptions: LRUCache.GetOptions = {},\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      if (fn(value, this.#keyList[i] as K, this)) {\n        return this.get(this.#keyList[i] as K, getOptions)\n      }\n    }\n  }\n\n  /**\n   * Call the supplied function on each item in the cache, in order from most\n   * recently used to least recently used.\n   *\n   * `fn` is called as `fn(value, key, cache)`.\n   *\n   * If `thisp` is provided, function will be called in the `this`-context of\n   * the provided object, or the cache if no `thisp` object is provided.\n   *\n   * Does not update age or recenty of use, or iterate over stale values.\n   */\n  forEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this,\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * The same as {@link LRUCache.forEach} but items are iterated over in\n   * reverse order.  (ie, less recently used items are iterated over first.)\n   */\n  rforEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this,\n  ) {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * Delete any stale entries. Returns true if anything was removed,\n   * false otherwise.\n   */\n  purgeStale() {\n    let deleted = false\n    for (const i of this.#rindexes({ allowStale: true })) {\n      if (this.#isStale(i)) {\n        this.#delete(this.#keyList[i] as K, 'expire')\n        deleted = true\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Get the extended info about a given entry, to get its value, size, and\n   * TTL info simultaneously. Returns `undefined` if the key is not present.\n   *\n   * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n   * serialization, the `start` value is always the current timestamp, and the\n   * `ttl` is a calculated remaining time to live (negative if expired).\n   *\n   * Always returns stale values, if their info is found in the cache, so be\n   * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n   * if relevant.\n   */\n  info(key: K): LRUCache.Entry | undefined {\n    const i = this.#keyMap.get(key)\n    if (i === undefined) return undefined\n    const v = this.#valList[i]\n    /* c8 ignore start - this isn't tested for the info function,\n     * but it's the same logic as found in other places. */\n    const value: V | undefined =\n      this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n    if (value === undefined) return undefined\n    /* c8 ignore end */\n    const entry: LRUCache.Entry = { value }\n    if (this.#ttls && this.#starts) {\n      const ttl = this.#ttls[i]\n      const start = this.#starts[i]\n      if (ttl && start) {\n        const remain = ttl - (this.#perf.now() - start)\n        entry.ttl = remain\n        entry.start = Date.now()\n      }\n    }\n    if (this.#sizes) {\n      entry.size = this.#sizes[i]\n    }\n    return entry\n  }\n\n  /**\n   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n   * passed to {@link LRUCache#load}.\n   *\n   * The `start` fields are calculated relative to a portable `Date.now()`\n   * timestamp, even if `performance.now()` is available.\n   *\n   * Stale entries are always included in the `dump`, even if\n   * {@link LRUCache.OptionsBase.allowStale} is false.\n   *\n   * Note: this returns an actual array, not a generator, so it can be more\n   * easily passed around.\n   */\n  dump() {\n    const arr: [K, LRUCache.Entry][] = []\n    for (const i of this.#indexes({ allowStale: true })) {\n      const key = this.#keyList[i]\n      const v = this.#valList[i]\n      const value: V | undefined =\n        this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined || key === undefined) continue\n      const entry: LRUCache.Entry = { value }\n      if (this.#ttls && this.#starts) {\n        entry.ttl = this.#ttls[i]\n        // always dump the start relative to a portable timestamp\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = this.#perf.now() - (this.#starts[i] as number)\n        entry.start = Math.floor(Date.now() - age)\n      }\n      if (this.#sizes) {\n        entry.size = this.#sizes[i]\n      }\n      arr.unshift([key, entry])\n    }\n    return arr\n  }\n\n  /**\n   * Reset the cache and load in the items in entries in the order listed.\n   *\n   * The shape of the resulting cache may be different if the same options are\n   * not used in both caches.\n   *\n   * The `start` fields are assumed to be calculated relative to a portable\n   * `Date.now()` timestamp, even if `performance.now()` is available.\n   */\n  load(arr: [K, LRUCache.Entry][]) {\n    this.clear()\n    for (const [key, entry] of arr) {\n      if (entry.start) {\n        // entry.start is a portable timestamp, but we may be using\n        // node's performance.now(), so calculate the offset, so that\n        // we get the intended remaining TTL, no matter how long it's\n        // been on ice.\n        //\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = Date.now() - entry.start\n        entry.start = this.#perf.now() - age\n      }\n      this.set(key, entry.value, entry)\n    }\n  }\n\n  /**\n   * Add a value to the cache.\n   *\n   * Note: if `undefined` is specified as a value, this is an alias for\n   * {@link LRUCache#delete}\n   *\n   * Fields on the {@link LRUCache.SetOptions} options param will override\n   * their corresponding values in the constructor options for the scope\n   * of this single `set()` operation.\n   *\n   * If `start` is provided, then that will set the effective start\n   * time for the TTL calculation. Note that this must be a previous\n   * value of `performance.now()` if supported, or a previous value of\n   * `Date.now()` if not.\n   *\n   * Options object may also include `size`, which will prevent\n   * calling the `sizeCalculation` function and just use the specified\n   * number if it is a positive integer, and `noDisposeOnSet` which\n   * will prevent calling a `dispose` function in the case of\n   * overwrites.\n   *\n   * If the `size` (or return value of `sizeCalculation`) for a given\n   * entry is greater than `maxEntrySize`, then the item will not be\n   * added to the cache.\n   *\n   * Will update the recency of the entry.\n   *\n   * If the value is `undefined`, then this is an alias for\n   * `cache.delete(key)`. `undefined` is never stored in the cache.\n   */\n  set(\n    k: K,\n    v: V | BackgroundFetch | undefined,\n    setOptions: LRUCache.SetOptions = {},\n  ) {\n    if (v === undefined) {\n      this.delete(k)\n      return this\n    }\n    const {\n      ttl = this.ttl,\n      start,\n      noDisposeOnSet = this.noDisposeOnSet,\n      sizeCalculation = this.sizeCalculation,\n      status,\n    } = setOptions\n    let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n    const size = this.#requireSize(\n      k,\n      v,\n      setOptions.size || 0,\n      sizeCalculation,\n    )\n    // if the item doesn't fit, don't do anything\n    // NB: maxEntrySize set to maxSize by default\n    if (this.maxEntrySize && size > this.maxEntrySize) {\n      if (status) {\n        status.set = 'miss'\n        status.maxEntrySizeExceeded = true\n      }\n      // have to delete, in case something is there already.\n      this.#delete(k, 'set')\n      return this\n    }\n    let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n    if (index === undefined) {\n      // addition\n      index = (\n        this.#size === 0 ? this.#tail\n        : this.#free.length !== 0 ? this.#free.pop()\n        : this.#size === this.#max ? this.#evict(false)\n        : this.#size) as Index\n      this.#keyList[index] = k\n      this.#valList[index] = v\n      this.#keyMap.set(k, index)\n      this.#next[this.#tail] = index\n      this.#prev[index] = this.#tail\n      this.#tail = index\n      this.#size++\n      this.#addItemSize(index, size, status)\n      if (status) status.set = 'add'\n      noUpdateTTL = false\n      if (this.#hasOnInsert) {\n        this.#onInsert?.(v as V, k, 'add')\n      }\n    } else {\n      // update\n      this.#moveToTail(index)\n      const oldVal = this.#valList[index] as V | BackgroundFetch\n      if (v !== oldVal) {\n        if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n          oldVal.__abortController.abort(new Error('replaced'))\n          const { __staleWhileFetching: s } = oldVal\n          if (s !== undefined && !noDisposeOnSet) {\n            if (this.#hasDispose) {\n              this.#dispose?.(s as V, k, 'set')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([s as V, k, 'set'])\n            }\n          }\n        } else if (!noDisposeOnSet) {\n          if (this.#hasDispose) {\n            this.#dispose?.(oldVal as V, k, 'set')\n          }\n          if (this.#hasDisposeAfter) {\n            this.#disposed?.push([oldVal as V, k, 'set'])\n          }\n        }\n        this.#removeItemSize(index)\n        this.#addItemSize(index, size, status)\n        this.#valList[index] = v\n        if (status) {\n          status.set = 'replace'\n          const oldValue =\n            oldVal && this.#isBackgroundFetch(oldVal) ?\n              oldVal.__staleWhileFetching\n            : oldVal\n          if (oldValue !== undefined) status.oldValue = oldValue\n        }\n      } else if (status) {\n        status.set = 'update'\n      }\n\n      if (this.#hasOnInsert) {\n        this.onInsert?.(v as V, k, v === oldVal ? 'update' : 'replace')\n      }\n    }\n    if (ttl !== 0 && !this.#ttls) {\n      this.#initializeTTLTracking()\n    }\n    if (this.#ttls) {\n      if (!noUpdateTTL) {\n        this.#setItemTTL(index, ttl, start)\n      }\n      if (status) this.#statusTTL(status, index)\n    }\n    if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return this\n  }\n\n  /**\n   * Evict the least recently used item, returning its value or\n   * `undefined` if cache is empty.\n   */\n  pop(): V | undefined {\n    try {\n      while (this.#size) {\n        const val = this.#valList[this.#head]\n        this.#evict(true)\n        if (this.#isBackgroundFetch(val)) {\n          if (val.__staleWhileFetching) {\n            return val.__staleWhileFetching\n          }\n        } else if (val !== undefined) {\n          return val\n        }\n      }\n    } finally {\n      if (this.#hasDisposeAfter && this.#disposed) {\n        const dt = this.#disposed\n        let task: DisposeTask | undefined\n        while ((task = dt?.shift())) {\n          this.#disposeAfter?.(...task)\n        }\n      }\n    }\n  }\n\n  #evict(free: boolean) {\n    const head = this.#head\n    const k = this.#keyList[head] as K\n    const v = this.#valList[head] as V\n    if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n      v.__abortController.abort(new Error('evicted'))\n    } else if (this.#hasDispose || this.#hasDisposeAfter) {\n      if (this.#hasDispose) {\n        this.#dispose?.(v, k, 'evict')\n      }\n      if (this.#hasDisposeAfter) {\n        this.#disposed?.push([v, k, 'evict'])\n      }\n    }\n    this.#removeItemSize(head)\n    if (this.#autopurgeTimers?.[head]) {\n      clearTimeout(this.#autopurgeTimers[head])\n      this.#autopurgeTimers[head] = undefined\n    }\n    // if we aren't about to use the index, then null these out\n    if (free) {\n      this.#keyList[head] = undefined\n      this.#valList[head] = undefined\n      this.#free.push(head)\n    }\n    if (this.#size === 1) {\n      this.#head = this.#tail = 0 as Index\n      this.#free.length = 0\n    } else {\n      this.#head = this.#next[head] as Index\n    }\n    this.#keyMap.delete(k)\n    this.#size--\n    return head\n  }\n\n  /**\n   * Check if a key is in the cache, without updating the recency of use.\n   * Will return false if the item is stale, even though it is technically\n   * in the cache.\n   *\n   * Check if a key is in the cache, without updating the recency of\n   * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n   * to `true` in either the options or the constructor.\n   *\n   * Will return `false` if the item is stale, even though it is technically in\n   * the cache. The difference can be determined (if it matters) by using a\n   * `status` argument, and inspecting the `has` field.\n   *\n   * Will not update item age unless\n   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n   */\n  has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const v = this.#valList[index]\n      if (\n        this.#isBackgroundFetch(v) &&\n        v.__staleWhileFetching === undefined\n      ) {\n        return false\n      }\n      if (!this.#isStale(index)) {\n        if (updateAgeOnHas) {\n          this.#updateItemAge(index)\n        }\n        if (status) {\n          status.has = 'hit'\n          this.#statusTTL(status, index)\n        }\n        return true\n      } else if (status) {\n        status.has = 'stale'\n        this.#statusTTL(status, index)\n      }\n    } else if (status) {\n      status.has = 'miss'\n    }\n    return false\n  }\n\n  /**\n   * Like {@link LRUCache#get} but doesn't update recency or delete stale\n   * items.\n   *\n   * Returns `undefined` if the item is stale, unless\n   * {@link LRUCache.OptionsBase.allowStale} is set.\n   */\n  peek(k: K, peekOptions: LRUCache.PeekOptions = {}) {\n    const { allowStale = this.allowStale } = peekOptions\n    const index = this.#keyMap.get(k)\n    if (index === undefined || (!allowStale && this.#isStale(index))) {\n      return\n    }\n    const v = this.#valList[index]\n    // either stale and allowed, or forcing a refresh of non-stale value\n    return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n  }\n\n  #backgroundFetch(\n    k: K,\n    index: Index | undefined,\n    options: LRUCache.FetchOptions,\n    context: any,\n  ): BackgroundFetch {\n    const v = index === undefined ? undefined : this.#valList[index]\n    if (this.#isBackgroundFetch(v)) {\n      return v\n    }\n\n    const ac = new AC()\n    const { signal } = options\n    // when/if our AC signals, then stop listening to theirs.\n    signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n      signal: ac.signal,\n    })\n\n    const fetchOpts = {\n      signal: ac.signal,\n      options,\n      context,\n    }\n\n    const cb = (v: V | undefined, updateCache = false): V | undefined => {\n      const { aborted } = ac.signal\n      const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n      const proceed = options.ignoreFetchAbort ||\n        !!(options.allowStaleOnFetchAbort && v !== undefined)\n      if (options.status) {\n        if (aborted && !updateCache) {\n          options.status.fetchAborted = true\n          options.status.fetchError = ac.signal.reason\n          if (ignoreAbort) options.status.fetchAbortIgnored = true\n        } else {\n          options.status.fetchResolved = true\n        }\n      }\n      if (aborted && !ignoreAbort && !updateCache) {\n        return fetchFail(ac.signal.reason, proceed)\n      }\n      // either we didn't abort, and are still here, or we did, and ignored\n      const bf = p as BackgroundFetch\n      // if nothing else has been written there but we're set to update the\n      // cache and ignore the abort, or if it's still pending on this specific\n      // background request, then write it to the cache.\n      const vl = this.#valList[index as Index]\n      if (vl === p || (ignoreAbort && updateCache && vl === undefined)) {\n        if (v === undefined) {\n          if (bf.__staleWhileFetching !== undefined) {\n            this.#valList[index as Index] = bf.__staleWhileFetching\n          } else {\n            this.#delete(k, 'fetch')\n          }\n        } else {\n          if (options.status) options.status.fetchUpdated = true\n          this.set(k, v, fetchOpts.options)\n        }\n      }\n      return v\n    }\n\n    const eb = (er: any) => {\n      if (options.status) {\n        options.status.fetchRejected = true\n        options.status.fetchError = er\n      }\n      // do not pass go, do not collect $200\n      return fetchFail(er, false)\n    }\n\n    const fetchFail = (er: any, proceed: boolean): V | undefined => {\n      const { aborted } = ac.signal\n      const allowStaleAborted = aborted && options.allowStaleOnFetchAbort\n      const allowStale =\n        allowStaleAborted || options.allowStaleOnFetchRejection\n      const noDelete = allowStale || options.noDeleteOnFetchRejection\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        // if we allow stale on fetch rejections, then we need to ensure that\n        // the stale value is not removed from the cache when the fetch fails.\n        const del = !noDelete ||\n          !proceed && bf.__staleWhileFetching === undefined\n        if (del) {\n          this.#delete(k, 'fetch')\n        } else if (!allowStaleAborted) {\n          // still replace the *promise* with the stale value,\n          // since we are done with the promise at this point.\n          // leave it untouched if we're still waiting for an\n          // aborted background fetch that hasn't yet returned.\n          this.#valList[index as Index] = bf.__staleWhileFetching\n        }\n      }\n      if (allowStale) {\n        if (options.status && bf.__staleWhileFetching !== undefined) {\n          options.status.returnedStale = true\n        }\n        return bf.__staleWhileFetching\n      } else if (bf.__returned === bf) {\n        throw er\n      }\n    }\n\n    const pcall = (\n      res: (v: V | undefined) => void,\n      rej: (e: any) => void,\n    ) => {\n      const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n      if (fmp && fmp instanceof Promise) {\n        fmp.then(v => res(v === undefined ? undefined : v), rej)\n      }\n      // ignored, we go until we finish, regardless.\n      // defer check until we are actually aborting,\n      // so fetchMethod can override.\n      ac.signal.addEventListener('abort', () => {\n        if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {\n          res(undefined)\n          // when it eventually resolves, update the cache.\n          if (options.allowStaleOnFetchAbort) {\n            res = v => cb(v, true)\n          }\n        }\n      })\n    }\n\n    if (options.status) options.status.fetchDispatched = true\n    const p = new Promise(pcall).then(cb, eb)\n    const bf: BackgroundFetch = Object.assign(p, {\n      __abortController: ac,\n      __staleWhileFetching: v,\n      __returned: undefined,\n    })\n\n    if (index === undefined) {\n      // internal, don't expose status.\n      this.set(k, bf, { ...fetchOpts.options, status: undefined })\n      index = this.#keyMap.get(k)\n    } else {\n      this.#valList[index] = bf\n    }\n    return bf\n  }\n\n  #isBackgroundFetch(p: any): p is BackgroundFetch {\n    if (!this.#hasFetchMethod) return false\n    const b = p as BackgroundFetch\n    return (\n      !!b &&\n      b instanceof Promise &&\n      b.hasOwnProperty('__staleWhileFetching') &&\n      b.__abortController instanceof AC\n    )\n  }\n\n  /**\n   * Make an asynchronous cached fetch using the\n   * {@link LRUCache.OptionsBase.fetchMethod} function.\n   *\n   * If the value is in the cache and not stale, then the returned\n   * Promise resolves to the value.\n   *\n   * If not in the cache, or beyond its TTL staleness, then\n   * `fetchMethod(key, staleValue, { options, signal, context })` is\n   * called, and the value returned will be added to the cache once\n   * resolved.\n   *\n   * If called with `allowStale`, and an asynchronous fetch is\n   * currently in progress to reload a stale value, then the former\n   * stale value will be returned.\n   *\n   * If called with `forceRefresh`, then the cached item will be\n   * re-fetched, even if it is not stale. However, if `allowStale` is also\n   * set, then the old value will still be returned. This is useful\n   * in cases where you want to force a reload of a cached value. If\n   * a background fetch is already in progress, then `forceRefresh`\n   * has no effect.\n   *\n   * If multiple fetches for the same key are issued, then they will all be\n   * coalesced into a single call to fetchMethod.\n   *\n   * Note that this means that handling options such as\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n   * {@link LRUCache.FetchOptions.signal},\n   * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n   * determined by the FIRST fetch() call for a given key.\n   *\n   * This is a known (fixable) shortcoming which will be addresed on when\n   * someone complains about it, as the fix would involve added complexity and\n   * may not be worth the costs for this edge case.\n   *\n   * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n   * effectively an alias for `Promise.resolve(cache.get(key))`.\n   *\n   * When the fetch method resolves to a value, if the fetch has not\n   * been aborted due to deletion, eviction, or being overwritten,\n   * then it is added to the cache using the options provided.\n   *\n   * If the key is evicted or deleted before the `fetchMethod`\n   * resolves, then the AbortSignal passed to the `fetchMethod` will\n   * receive an `abort` event, and the promise returned by `fetch()`\n   * will reject with the reason for the abort.\n   *\n   * If a `signal` is passed to the `fetch()` call, then aborting the\n   * signal will abort the fetch and cause the `fetch()` promise to\n   * reject with the reason provided.\n   *\n   * **Setting `context`**\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the {@link LRUCache} constructor, then all\n   * calls to `cache.fetch()` _must_ provide a `context` option. If\n   * set to `undefined` or `void`, then calls to fetch _must not_\n   * provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that\n   * might be relevant in the course of fetching the data. It is only\n   * relevant for the course of a single `fetch()` operation, and\n   * discarded afterwards.\n   *\n   * **Note: `fetch()` calls are inflight-unique**\n   *\n   * If you call `fetch()` multiple times with the same key value,\n   * then every call after the first will resolve on the same\n   * promise1,\n   * _even if they have different settings that would otherwise change\n   * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n   * or `ignoreFetchAbort`.\n   *\n   * In most cases, this is not a problem (in fact, only fetching\n   * something once is what you probably want, if you're caching in\n   * the first place). If you are changing the fetch() options\n   * dramatically between runs, there's a good chance that you might\n   * be trying to fit divergent semantics into a single object, and\n   * would be better off with multiple cache instances.\n   *\n   * **1**: Ie, they're not the \"same Promise\", but they resolve at\n   * the same time, because they're both waiting on the same\n   * underlying fetchMethod response.\n   */\n\n  fetch(\n    k: K,\n    fetchOptions: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n    : LRUCache.FetchOptionsWithContext,\n  ): Promise\n\n  // this overload not allowed if context is required\n  fetch(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    fetchOptions?: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n    : never,\n  ): Promise\n\n  async fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const {\n      // get options\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      // set options\n      ttl = this.ttl,\n      noDisposeOnSet = this.noDisposeOnSet,\n      size = 0,\n      sizeCalculation = this.sizeCalculation,\n      noUpdateTTL = this.noUpdateTTL,\n      // fetch exclusive options\n      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n      ignoreFetchAbort = this.ignoreFetchAbort,\n      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n      context,\n      forceRefresh = false,\n      status,\n      signal,\n    } = fetchOptions\n\n    if (!this.#hasFetchMethod) {\n      if (status) status.fetch = 'get'\n      return this.get(k, {\n        allowStale,\n        updateAgeOnGet,\n        noDeleteOnStaleGet,\n        status,\n      })\n    }\n\n    const options = {\n      allowStale,\n      updateAgeOnGet,\n      noDeleteOnStaleGet,\n      ttl,\n      noDisposeOnSet,\n      size,\n      sizeCalculation,\n      noUpdateTTL,\n      noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      status,\n      signal,\n    }\n\n    let index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.fetch = 'miss'\n      const p = this.#backgroundFetch(k, index, options, context)\n      return (p.__returned = p)\n    } else {\n      // in cache, maybe already fetching\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        const stale = allowStale && v.__staleWhileFetching !== undefined\n        if (status) {\n          status.fetch = 'inflight'\n          if (stale) status.returnedStale = true\n        }\n        return stale ? v.__staleWhileFetching : (v.__returned = v)\n      }\n\n      // if we force a refresh, that means do NOT serve the cached value,\n      // unless we are already in the process of refreshing the cache.\n      const isStale = this.#isStale(index)\n      if (!forceRefresh && !isStale) {\n        if (status) status.fetch = 'hit'\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        if (status) this.#statusTTL(status, index)\n        return v\n      }\n\n      // ok, it is stale or a forced refresh, and not already fetching.\n      // refresh the cache.\n      const p = this.#backgroundFetch(k, index, options, context)\n      const hasStale = p.__staleWhileFetching !== undefined\n      const staleVal = hasStale && allowStale\n      if (status) {\n        status.fetch = isStale ? 'stale' : 'refresh'\n        if (staleVal && isStale) status.returnedStale = true\n      }\n      return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n    }\n  }\n\n  /**\n   * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n   * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n   * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n   * because `ignoreFetchAbort` was specified (either to the constructor or\n   * in the {@link LRUCache.FetchOptions}). Also, the\n   * {@link LRUCache.OptionsBase.fetchMethod} may return `undefined` or `void`, making\n   * the test even more complicated.\n   *\n   * Because inferring the cases where `undefined` might be returned are so\n   * cumbersome, but testing for `undefined` can also be annoying, this method\n   * can be used, which will reject if `this.fetch()` resolves to undefined.\n   */\n  forceFetch(\n    k: K,\n    fetchOptions: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n    : LRUCache.FetchOptionsWithContext,\n  ): Promise\n  // this overload not allowed if context is required\n  forceFetch(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    fetchOptions?: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n    : never,\n  ): Promise\n  async forceFetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const v = await this.fetch(\n      k,\n      fetchOptions as unknown extends FC ? LRUCache.FetchOptions\n      : FC extends undefined | void ? LRUCache.FetchOptionsNoContext\n      : LRUCache.FetchOptionsWithContext,\n    )\n    if (v === undefined) throw new Error('fetch() returned undefined')\n    return v\n  }\n\n  /**\n   * If the key is found in the cache, then this is equivalent to\n   * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n   * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n   * _must_ provide a `context` option. If set to `undefined` or `void`, then\n   * calls to memo _must not_ provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that might be\n   * relevant in the course of fetching the data. It is only relevant for the\n   * course of a single `memo()` operation, and discarded afterwards.\n   */\n  memo(\n    k: K,\n    memoOptions: unknown extends FC ? LRUCache.MemoOptions\n    : FC extends undefined | void ? LRUCache.MemoOptionsNoContext\n    : LRUCache.MemoOptionsWithContext,\n  ): V\n  // this overload not allowed if context is required\n  memo(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    memoOptions?: unknown extends FC ? LRUCache.MemoOptions\n    : FC extends undefined | void ? LRUCache.MemoOptionsNoContext\n    : never,\n  ): V\n  memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n    const memoMethod = this.#memoMethod\n    if (!memoMethod) {\n      throw new Error('no memoMethod provided to constructor')\n    }\n    const { context, forceRefresh, ...options } = memoOptions\n    const v = this.get(k, options)\n    if (!forceRefresh && v !== undefined) return v\n    const vv = memoMethod(k, v, {\n      options,\n      context,\n    } as LRUCache.MemoizerOptions)\n    this.set(k, vv, options)\n    return vv\n  }\n\n  /**\n   * Return a value from the cache. Will update the recency of the cache\n   * entry found.\n   *\n   * If the key is not found, get() will return `undefined`.\n   */\n  get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const {\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      status,\n    } = getOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const value = this.#valList[index]\n      const fetching = this.#isBackgroundFetch(value)\n      if (status) this.#statusTTL(status, index)\n      if (this.#isStale(index)) {\n        if (status) status.get = 'stale'\n        // delete only if not an in-flight background fetch\n        if (!fetching) {\n          if (!noDeleteOnStaleGet) {\n            this.#delete(k, 'expire')\n          }\n          if (status && allowStale) status.returnedStale = true\n          return allowStale ? value : undefined\n        } else {\n          if (\n            status &&\n            allowStale &&\n            value.__staleWhileFetching !== undefined\n          ) {\n            status.returnedStale = true\n          }\n          return allowStale ? value.__staleWhileFetching : undefined\n        }\n      } else {\n        if (status) status.get = 'hit'\n        // if we're currently fetching it, we don't actually have it yet\n        // it's not stale, which means this isn't a staleWhileRefetching.\n        // If it's not stale, and fetching, AND has a __staleWhileFetching\n        // value, then that means the user fetched with {forceRefresh:true},\n        // so it's safe to return that value.\n        if (fetching) {\n          return value.__staleWhileFetching\n        }\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        return value\n      }\n    } else if (status) {\n      status.get = 'miss'\n    }\n  }\n\n  #connect(p: Index, n: Index) {\n    this.#prev[n] = p\n    this.#next[p] = n\n  }\n\n  #moveToTail(index: Index): void {\n    // if tail already, nothing to do\n    // if head, move head to next[index]\n    // else\n    //   move next[prev[index]] to next[index] (head has no prev)\n    //   move prev[next[index]] to prev[index]\n    // prev[index] = tail\n    // next[tail] = index\n    // tail = index\n    if (index !== this.#tail) {\n      if (index === this.#head) {\n        this.#head = this.#next[index] as Index\n      } else {\n        this.#connect(\n          this.#prev[index] as Index,\n          this.#next[index] as Index,\n        )\n      }\n      this.#connect(this.#tail, index)\n      this.#tail = index\n    }\n  }\n\n  /**\n   * Deletes a key out of the cache.\n   *\n   * Returns true if the key was deleted, false otherwise.\n   */\n  delete(k: K) {\n    return this.#delete(k, 'delete')\n  }\n\n  #delete(k: K, reason: LRUCache.DisposeReason) {\n    let deleted = false\n    if (this.#size !== 0) {\n      const index = this.#keyMap.get(k)\n      if (index !== undefined) {\n        if (this.#autopurgeTimers?.[index]) {\n          clearTimeout(this.#autopurgeTimers?.[index])\n          this.#autopurgeTimers[index] = undefined\n        }\n        deleted = true\n        if (this.#size === 1) {\n          this.#clear(reason)\n        } else {\n          this.#removeItemSize(index)\n          const v = this.#valList[index]\n          if (this.#isBackgroundFetch(v)) {\n            v.__abortController.abort(new Error('deleted'))\n          } else if (this.#hasDispose || this.#hasDisposeAfter) {\n            if (this.#hasDispose) {\n              this.#dispose?.(v as V, k, reason)\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([v as V, k, reason])\n            }\n          }\n          this.#keyMap.delete(k)\n          this.#keyList[index] = undefined\n          this.#valList[index] = undefined\n          if (index === this.#tail) {\n            this.#tail = this.#prev[index] as Index\n          } else if (index === this.#head) {\n            this.#head = this.#next[index] as Index\n          } else {\n            const pi = this.#prev[index] as number\n            this.#next[pi] = this.#next[index] as number\n            const ni = this.#next[index] as number\n            this.#prev[ni] = this.#prev[index] as number\n          }\n          this.#size--\n          this.#free.push(index)\n        }\n      }\n    }\n    if (this.#hasDisposeAfter && this.#disposed?.length) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Clear the cache entirely, throwing away all values.\n   */\n  clear() {\n    return this.#clear('delete')\n  }\n  #clear(reason: LRUCache.DisposeReason) {\n    for (const index of this.#rindexes({ allowStale: true })) {\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        v.__abortController.abort(new Error('deleted'))\n      } else {\n        const k = this.#keyList[index]\n        if (this.#hasDispose) {\n          this.#dispose?.(v as V, k as K, reason)\n        }\n        if (this.#hasDisposeAfter) {\n          this.#disposed?.push([v as V, k as K, reason])\n        }\n      }\n    }\n\n    this.#keyMap.clear()\n    this.#valList.fill(undefined)\n    this.#keyList.fill(undefined)\n    if (this.#ttls && this.#starts) {\n      this.#ttls.fill(0)\n      this.#starts.fill(0)\n      for (const t of this.#autopurgeTimers ?? []) {\n        if (t !== undefined) clearTimeout(t)\n      }\n      this.#autopurgeTimers?.fill(undefined)\n    }\n    if (this.#sizes) {\n      this.#sizes.fill(0)\n    }\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free.length = 0\n    this.#calculatedSize = 0\n    this.#size = 0\n    if (this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n  }\n}\n", "import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises || {}),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n  rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new LRUCache({ max: 2 ** 12 })\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new LRUCache({ max: 2 ** 12 })\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /* c8 ignore start */\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   *\n   * @deprecated\n   */\n  get path(): string {\n    return this.parentPath\n  }\n  /* c8 ignore stop */\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    if (rootPath === this.root.name) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(\n      rootPath,\n      this,\n    ).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    rootPath = rootPath\n      .toUpperCase()\n      .replace(/\\//g, '\\\\')\n      .replace(uncDriveRegexp, '$1\\\\')\n    return rootPath === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n", "const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n  s: any\n): s is Minipass.Readable | Minipass.Writable =>\n  !!s &&\n  typeof s === 'object' &&\n  (s instanceof Minipass ||\n    s instanceof Stream ||\n    isReadable(s) ||\n    isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Readable).pipe === 'function' &&\n  // node core Writable streams have a pipe() method, but it throws\n  (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Writable).write === 'function' &&\n  typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n  ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n  b instanceof ArrayBuffer ||\n  (!!b &&\n    typeof b === 'object' &&\n    b.constructor &&\n    b.constructor.name === 'ArrayBuffer' &&\n    b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n  !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n  /**\n   * end the destination stream when the source stream ends\n   */\n  end?: boolean\n  /**\n   * proxy errors from the source stream to the destination stream\n   */\n  proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n  src: Minipass\n  dest: Minipass\n  opts: PipeOptions\n  ondrain: () => any\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    this.src = src\n    this.dest = dest as Minipass\n    this.opts = opts\n    this.ondrain = () => src[RESUME]()\n    this.dest.on('drain', this.ondrain)\n  }\n  unpipe() {\n    this.dest.removeListener('drain', this.ondrain)\n  }\n  // only here for the prototype\n  /* c8 ignore start */\n  proxyErrors(_er: any) {}\n  /* c8 ignore stop */\n  end() {\n    this.unpipe()\n    if (this.opts.end) this.dest.end()\n  }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n  unpipe() {\n    this.src.removeListener('error', this.proxyErrors)\n    super.unpipe()\n  }\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    super(src, dest, opts)\n    this.proxyErrors = (er: Error) => this.dest.emit('error', er)\n    src.on('error', this.proxyErrors)\n  }\n}\n\nexport namespace Minipass {\n  /**\n   * Encoding used to create a stream that outputs strings rather than\n   * Buffer objects.\n   */\n  export type Encoding = BufferEncoding | 'buffer' | null\n\n  /**\n   * Any stream that Minipass can pipe into\n   */\n  export type Writable =\n    | Minipass\n    | NodeJS.WriteStream\n    | (NodeJS.WriteStream & { fd: number })\n    | (EventEmitter & {\n        end(): any\n        write(chunk: any, ...args: any[]): any\n      })\n\n  /**\n   * Any stream that can be read from\n   */\n  export type Readable =\n    | Minipass\n    | NodeJS.ReadStream\n    | (NodeJS.ReadStream & { fd: number })\n    | (EventEmitter & {\n        pause(): any\n        resume(): any\n        pipe(...destArgs: any[]): any\n      })\n\n  /**\n   * Utility type that can be iterated sync or async\n   */\n  export type DualIterable = Iterable & AsyncIterable\n\n  type EventArguments = Record\n\n  /**\n   * The listing of events that a Minipass class can emit.\n   * Extend this when extending the Minipass class, and pass as\n   * the third template argument.  The key is the name of the event,\n   * and the value is the argument list.\n   *\n   * Any undeclared events will still be allowed, but the handler will get\n   * arguments as `unknown[]`.\n   */\n  export interface Events\n    extends EventArguments {\n    readable: []\n    data: [chunk: RType]\n    error: [er: unknown]\n    abort: [reason: unknown]\n    drain: []\n    resume: []\n    end: []\n    finish: []\n    prefinish: []\n    close: []\n    [DESTROYED]: [er?: unknown]\n    [ERROR]: [er: unknown]\n  }\n\n  /**\n   * String or buffer-like data that can be joined and sliced\n   */\n  export type ContiguousData =\n    | Buffer\n    | ArrayBufferLike\n    | ArrayBufferView\n    | string\n  export type BufferOrString = Buffer | string\n\n  /**\n   * Options passed to the Minipass constructor.\n   */\n  export type SharedOptions = {\n    /**\n     * Defer all data emission and other events until the end of the\n     * current tick, similar to Node core streams\n     */\n    async?: boolean\n    /**\n     * A signal which will abort the stream\n     */\n    signal?: AbortSignal\n    /**\n     * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n     * emit Buffer objects rather than strings.\n     *\n     * Conflicts with `objectMode`\n     */\n    encoding?: BufferEncoding | null | 'buffer'\n    /**\n     * Output data exactly as it was written, supporting non-buffer/string\n     * data (such as arbitrary objects, falsey values, etc.)\n     *\n     * Conflicts with `encoding`\n     */\n    objectMode?: boolean\n  }\n\n  /**\n   * Options for a string encoded output\n   */\n  export type EncodingOptions = SharedOptions & {\n    encoding: BufferEncoding\n    objectMode?: false\n  }\n\n  /**\n   * Options for contiguous data buffer output\n   */\n  export type BufferOptions = SharedOptions & {\n    encoding?: null | 'buffer'\n    objectMode?: false\n  }\n\n  /**\n   * Options for objectMode arbitrary output\n   */\n  export type ObjectModeOptions = SharedOptions & {\n    objectMode: true\n    encoding?: null\n  }\n\n  /**\n   * Utility type to determine allowed options based on read type\n   */\n  export type Options =\n    | ObjectModeOptions\n    | (T extends string\n        ? EncodingOptions\n        : T extends Buffer\n        ? BufferOptions\n        : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n  !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n    RType extends unknown = Buffer,\n    WType extends unknown = RType extends Minipass.BufferOrString\n      ? Minipass.ContiguousData\n      : RType,\n    Events extends Minipass.Events = Minipass.Events\n  >\n  extends EventEmitter\n  implements Minipass.DualIterable\n{\n  [FLOWING]: boolean = false;\n  [PAUSED]: boolean = false;\n  [PIPES]: Pipe[] = [];\n  [BUFFER]: RType[] = [];\n  [OBJECTMODE]: boolean;\n  [ENCODING]: BufferEncoding | null;\n  [ASYNC]: boolean;\n  [DECODER]: SD | null;\n  [EOF]: boolean = false;\n  [EMITTED_END]: boolean = false;\n  [EMITTING_END]: boolean = false;\n  [CLOSED]: boolean = false;\n  [EMITTED_ERROR]: unknown = null;\n  [BUFFERLENGTH]: number = 0;\n  [DESTROYED]: boolean = false;\n  [SIGNAL]?: AbortSignal;\n  [ABORTED]: boolean = false;\n  [DATALISTENERS]: number = 0;\n  [DISCARDED]: boolean = false\n\n  /**\n   * true if the stream can be written\n   */\n  writable: boolean = true\n  /**\n   * true if the stream can be read\n   */\n  readable: boolean = true\n\n  /**\n   * If `RType` is Buffer, then options do not need to be provided.\n   * Otherwise, an options object must be provided to specify either\n   * {@link Minipass.SharedOptions.objectMode} or\n   * {@link Minipass.SharedOptions.encoding}, as appropriate.\n   */\n  constructor(\n    ...args:\n      | [Minipass.ObjectModeOptions]\n      | (RType extends Buffer\n          ? [] | [Minipass.Options]\n          : [Minipass.Options])\n  ) {\n    const options: Minipass.Options = (args[0] ||\n      {}) as Minipass.Options\n    super()\n    if (options.objectMode && typeof options.encoding === 'string') {\n      throw new TypeError(\n        'Encoding and objectMode may not be used together'\n      )\n    }\n    if (isObjectModeOptions(options)) {\n      this[OBJECTMODE] = true\n      this[ENCODING] = null\n    } else if (isEncodingOptions(options)) {\n      this[ENCODING] = options.encoding\n      this[OBJECTMODE] = false\n    } else {\n      this[OBJECTMODE] = false\n      this[ENCODING] = null\n    }\n    this[ASYNC] = !!options.async\n    this[DECODER] = this[ENCODING]\n      ? (new StringDecoder(this[ENCODING]) as SD)\n      : null\n\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposeBuffer === true) {\n      Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n    }\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposePipes === true) {\n      Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n    }\n\n    const { signal } = options\n    if (signal) {\n      this[SIGNAL] = signal\n      if (signal.aborted) {\n        this[ABORT]()\n      } else {\n        signal.addEventListener('abort', () => this[ABORT]())\n      }\n    }\n  }\n\n  /**\n   * The amount of data stored in the buffer waiting to be read.\n   *\n   * For Buffer strings, this will be the total byte length.\n   * For string encoding streams, this will be the string character length,\n   * according to JavaScript's `string.length` logic.\n   * For objectMode streams, this is a count of the items waiting to be\n   * emitted.\n   */\n  get bufferLength() {\n    return this[BUFFERLENGTH]\n  }\n\n  /**\n   * The `BufferEncoding` currently in use, or `null`\n   */\n  get encoding() {\n    return this[ENCODING]\n  }\n\n  /**\n   * @deprecated - This is a read only property\n   */\n  set encoding(_enc) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * @deprecated - Encoding may only be set at instantiation time\n   */\n  setEncoding(_enc: Minipass.Encoding) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * True if this is an objectMode stream\n   */\n  get objectMode() {\n    return this[OBJECTMODE]\n  }\n\n  /**\n   * @deprecated - This is a read-only property\n   */\n  set objectMode(_om) {\n    throw new Error('objectMode must be set at instantiation time')\n  }\n\n  /**\n   * true if this is an async stream\n   */\n  get ['async'](): boolean {\n    return this[ASYNC]\n  }\n  /**\n   * Set to true to make this stream async.\n   *\n   * Once set, it cannot be unset, as this would potentially cause incorrect\n   * behavior.  Ie, a sync stream can be made async, but an async stream\n   * cannot be safely made sync.\n   */\n  set ['async'](a: boolean) {\n    this[ASYNC] = this[ASYNC] || !!a\n  }\n\n  // drop everything and get out of the flow completely\n  [ABORT]() {\n    this[ABORTED] = true\n    this.emit('abort', this[SIGNAL]?.reason)\n    this.destroy(this[SIGNAL]?.reason)\n  }\n\n  /**\n   * True if the stream has been aborted.\n   */\n  get aborted() {\n    return this[ABORTED]\n  }\n  /**\n   * No-op setter. Stream aborted status is set via the AbortSignal provided\n   * in the constructor options.\n   */\n  set aborted(_) {}\n\n  /**\n   * Write data into the stream\n   *\n   * If the chunk written is a string, and encoding is not specified, then\n   * `utf8` will be assumed. If the stream encoding matches the encoding of\n   * a written string, and the state of the string decoder allows it, then\n   * the string will be passed through to either the output or the internal\n   * buffer without any processing. Otherwise, it will be turned into a\n   * Buffer object for processing into the desired encoding.\n   *\n   * If provided, `cb` function is called immediately before return for\n   * sync streams, or on next tick for async streams, because for this\n   * base class, a chunk is considered \"processed\" once it is accepted\n   * and either emitted or buffered. That is, the callback does not indicate\n   * that the chunk has been eventually emitted, though of course child\n   * classes can override this function to do whatever processing is required\n   * and call `super.write(...)` only once processing is completed.\n   */\n  write(chunk: WType, cb?: () => void): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding,\n    cb?: () => void\n  ): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): boolean {\n    if (this[ABORTED]) return false\n    if (this[EOF]) throw new Error('write after end')\n\n    if (this[DESTROYED]) {\n      this.emit(\n        'error',\n        Object.assign(\n          new Error('Cannot call write after a stream was destroyed'),\n          { code: 'ERR_STREAM_DESTROYED' }\n        )\n      )\n      return true\n    }\n\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n\n    if (!encoding) encoding = 'utf8'\n\n    const fn = this[ASYNC] ? defer : nodefer\n\n    // convert array buffers and typed array views into buffers\n    // at some point in the future, we may want to do the opposite!\n    // leave strings and buffers as-is\n    // anything is only allowed if in object mode, so throw\n    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n      if (isArrayBufferView(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(\n          chunk.buffer,\n          chunk.byteOffset,\n          chunk.byteLength\n        )\n      } else if (isArrayBufferLike(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(chunk)\n      } else if (typeof chunk !== 'string') {\n        throw new Error(\n          'Non-contiguous data written to non-objectMode stream'\n        )\n      }\n    }\n\n    // handle object mode up front, since it's simpler\n    // this yields better performance, fewer checks later.\n    if (this[OBJECTMODE]) {\n      // maybe impossible?\n      /* c8 ignore start */\n      if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n      /* c8 ignore stop */\n\n      if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n      else this[BUFFERPUSH](chunk as unknown as RType)\n\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n      if (cb) fn(cb)\n\n      return this[FLOWING]\n    }\n\n    // at this point the chunk is a buffer or string\n    // don't buffer it up or send it to the decoder\n    if (!(chunk as Minipass.BufferOrString).length) {\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n      if (cb) fn(cb)\n      return this[FLOWING]\n    }\n\n    // fast-path writing strings of same encoding to a stream with\n    // an empty buffer, skipping the buffer/decoder dance\n    if (\n      typeof chunk === 'string' &&\n      // unless it is a string already ready for us to use\n      !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n    ) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = Buffer.from(chunk, encoding)\n    }\n\n    if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = this[DECODER].write(chunk)\n    }\n\n    // Note: flushing CAN potentially switch us into not-flowing mode\n    if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n    if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n    else this[BUFFERPUSH](chunk as unknown as RType)\n\n    if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n    if (cb) fn(cb)\n\n    return this[FLOWING]\n  }\n\n  /**\n   * Low-level explicit read method.\n   *\n   * In objectMode, the argument is ignored, and one item is returned if\n   * available.\n   *\n   * `n` is the number of bytes (or in the case of encoding streams,\n   * characters) to consume. If `n` is not provided, then the entire buffer\n   * is returned, or `null` is returned if no data is available.\n   *\n   * If `n` is greater that the amount of data in the internal buffer,\n   * then `null` is returned.\n   */\n  read(n?: number | null): RType | null {\n    if (this[DESTROYED]) return null\n    this[DISCARDED] = false\n\n    if (\n      this[BUFFERLENGTH] === 0 ||\n      n === 0 ||\n      (n && n > this[BUFFERLENGTH])\n    ) {\n      this[MAYBE_EMIT_END]()\n      return null\n    }\n\n    if (this[OBJECTMODE]) n = null\n\n    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n      // not object mode, so if we have an encoding, then RType is string\n      // otherwise, must be Buffer\n      this[BUFFER] = [\n        (this[ENCODING]\n          ? this[BUFFER].join('')\n          : Buffer.concat(\n              this[BUFFER] as Buffer[],\n              this[BUFFERLENGTH]\n            )) as RType,\n      ]\n    }\n\n    const ret = this[READ](n || null, this[BUFFER][0] as RType)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [READ](n: number | null, chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n    else {\n      const c = chunk as Minipass.BufferOrString\n      if (n === c.length || n === null) this[BUFFERSHIFT]()\n      else if (typeof c === 'string') {\n        this[BUFFER][0] = c.slice(n) as RType\n        chunk = c.slice(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      } else {\n        this[BUFFER][0] = c.subarray(n) as RType\n        chunk = c.subarray(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      }\n    }\n\n    this.emit('data', chunk)\n\n    if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n    return chunk\n  }\n\n  /**\n   * End the stream, optionally providing a final write.\n   *\n   * See {@link Minipass#write} for argument descriptions\n   */\n  end(cb?: () => void): this\n  end(chunk: WType, cb?: () => void): this\n  end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n  end(\n    chunk?: WType | (() => void),\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): this {\n    if (typeof chunk === 'function') {\n      cb = chunk as () => void\n      chunk = undefined\n    }\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n    if (chunk !== undefined) this.write(chunk, encoding)\n    if (cb) this.once('end', cb)\n    this[EOF] = true\n    this.writable = false\n\n    // if we haven't written anything, then go ahead and emit,\n    // even if we're not reading.\n    // we'll re-emit if a new 'end' listener is added anyway.\n    // This makes MP more suitable to write-only use cases.\n    if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n    return this\n  }\n\n  // don't let the internal resume be overwritten\n  [RESUME]() {\n    if (this[DESTROYED]) return\n\n    if (!this[DATALISTENERS] && !this[PIPES].length) {\n      this[DISCARDED] = true\n    }\n    this[PAUSED] = false\n    this[FLOWING] = true\n    this.emit('resume')\n    if (this[BUFFER].length) this[FLUSH]()\n    else if (this[EOF]) this[MAYBE_EMIT_END]()\n    else this.emit('drain')\n  }\n\n  /**\n   * Resume the stream if it is currently in a paused state\n   *\n   * If called when there are no pipe destinations or `data` event listeners,\n   * this will place the stream in a \"discarded\" state, where all data will\n   * be thrown away. The discarded state is removed if a pipe destination or\n   * data handler is added, if pause() is called, or if any synchronous or\n   * asynchronous iteration is started.\n   */\n  resume() {\n    return this[RESUME]()\n  }\n\n  /**\n   * Pause the stream\n   */\n  pause() {\n    this[FLOWING] = false\n    this[PAUSED] = true\n    this[DISCARDED] = false\n  }\n\n  /**\n   * true if the stream has been forcibly destroyed\n   */\n  get destroyed() {\n    return this[DESTROYED]\n  }\n\n  /**\n   * true if the stream is currently in a flowing state, meaning that\n   * any writes will be immediately emitted.\n   */\n  get flowing() {\n    return this[FLOWING]\n  }\n\n  /**\n   * true if the stream is currently in a paused state\n   */\n  get paused() {\n    return this[PAUSED]\n  }\n\n  [BUFFERPUSH](chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n    else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n    this[BUFFER].push(chunk)\n  }\n\n  [BUFFERSHIFT](): RType {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n    else\n      this[BUFFERLENGTH] -= (\n        this[BUFFER][0] as Minipass.BufferOrString\n      ).length\n    return this[BUFFER].shift() as RType\n  }\n\n  [FLUSH](noDrain: boolean = false) {\n    do {} while (\n      this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n      this[BUFFER].length\n    )\n\n    if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n  }\n\n  [FLUSHCHUNK](chunk: RType) {\n    this.emit('data', chunk)\n    return this[FLOWING]\n  }\n\n  /**\n   * Pipe all data emitted by this stream into the destination provided.\n   *\n   * Triggers the flow of data.\n   */\n  pipe(dest: W, opts?: PipeOptions): W {\n    if (this[DESTROYED]) return dest\n    this[DISCARDED] = false\n\n    const ended = this[EMITTED_END]\n    opts = opts || {}\n    if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n    else opts.end = opts.end !== false\n    opts.proxyErrors = !!opts.proxyErrors\n\n    // piping an ended stream ends immediately\n    if (ended) {\n      if (opts.end) dest.end()\n    } else {\n      // \"as\" here just ignores the WType, which pipes don't care about,\n      // since they're only consuming from us, and writing to the dest\n      this[PIPES].push(\n        !opts.proxyErrors\n          ? new Pipe(this as Minipass, dest, opts)\n          : new PipeProxyErrors(this as Minipass, dest, opts)\n      )\n      if (this[ASYNC]) defer(() => this[RESUME]())\n      else this[RESUME]()\n    }\n\n    return dest\n  }\n\n  /**\n   * Fully unhook a piped destination stream.\n   *\n   * If the destination stream was the only consumer of this stream (ie,\n   * there are no other piped destinations or `'data'` event listeners)\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  unpipe(dest: W) {\n    const p = this[PIPES].find(p => p.dest === dest)\n    if (p) {\n      if (this[PIPES].length === 1) {\n        if (this[FLOWING] && this[DATALISTENERS] === 0) {\n          this[FLOWING] = false\n        }\n        this[PIPES] = []\n      } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n      p.unpipe()\n    }\n  }\n\n  /**\n   * Alias for {@link Minipass#on}\n   */\n  addListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    return this.on(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.on`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * - Adding a 'data' event handler will trigger the flow of data\n   *\n   * - Adding a 'readable' event handler when there is data waiting to be read\n   *   will cause 'readable' to be emitted immediately.\n   *\n   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n   *   already passed will cause the event to be emitted immediately and all\n   *   handlers removed.\n   *\n   * - Adding an 'error' event handler after an error has been emitted will\n   *   cause the event to be re-emitted immediately with the error previously\n   *   raised.\n   */\n  on(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    const ret = super.on(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    if (ev === 'data') {\n      this[DISCARDED] = false\n      this[DATALISTENERS]++\n      if (!this[PIPES].length && !this[FLOWING]) {\n        this[RESUME]()\n      }\n    } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n      super.emit('readable')\n    } else if (isEndish(ev) && this[EMITTED_END]) {\n      super.emit(ev)\n      this.removeAllListeners(ev)\n    } else if (ev === 'error' && this[EMITTED_ERROR]) {\n      const h = handler as (...a: Events['error']) => any\n      if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n      else h.call(this, this[EMITTED_ERROR])\n    }\n    return ret\n  }\n\n  /**\n   * Alias for {@link Minipass#off}\n   */\n  removeListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    return this.off(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.off`\n   *\n   * If a 'data' event handler is removed, and it was the last consumer\n   * (ie, there are no pipe destinations or other 'data' event listeners),\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  off(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    const ret = super.off(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    // if we previously had listeners, and now we don't, and we don't\n    // have any pipes, then stop the flow, unless it's been explicitly\n    // put in a discarded flowing state via stream.resume().\n    if (ev === 'data') {\n      this[DATALISTENERS] = this.listeners('data').length\n      if (\n        this[DATALISTENERS] === 0 &&\n        !this[DISCARDED] &&\n        !this[PIPES].length\n      ) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.removeAllListeners`\n   *\n   * If all 'data' event handlers are removed, and they were the last consumer\n   * (ie, there are no pipe destinations), then the flow of data will stop\n   * until there is another consumer or {@link Minipass#resume} is explicitly\n   * called.\n   */\n  removeAllListeners(ev?: Event) {\n    const ret = super.removeAllListeners(ev as string | symbol | undefined)\n    if (ev === 'data' || ev === undefined) {\n      this[DATALISTENERS] = 0\n      if (!this[DISCARDED] && !this[PIPES].length) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * true if the 'end' event has been emitted\n   */\n  get emittedEnd() {\n    return this[EMITTED_END]\n  }\n\n  [MAYBE_EMIT_END]() {\n    if (\n      !this[EMITTING_END] &&\n      !this[EMITTED_END] &&\n      !this[DESTROYED] &&\n      this[BUFFER].length === 0 &&\n      this[EOF]\n    ) {\n      this[EMITTING_END] = true\n      this.emit('end')\n      this.emit('prefinish')\n      this.emit('finish')\n      if (this[CLOSED]) this.emit('close')\n      this[EMITTING_END] = false\n    }\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.emit`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * If the stream has been destroyed, and the event is something other\n   * than 'close' or 'error', then `false` is returned and no handlers\n   * are called.\n   *\n   * If the event is 'end', and has already been emitted, then the event\n   * is ignored. If the stream is in a paused or non-flowing state, then\n   * the event will be deferred until data flow resumes. If the stream is\n   * async, then handlers will be called on the next tick rather than\n   * immediately.\n   *\n   * If the event is 'close', and 'end' has not yet been emitted, then\n   * the event will be deferred until after 'end' is emitted.\n   *\n   * If the event is 'error', and an AbortSignal was provided for the stream,\n   * and there are no listeners, then the event is ignored, matching the\n   * behavior of node core streams in the presense of an AbortSignal.\n   *\n   * If the event is 'finish' or 'prefinish', then all listeners will be\n   * removed after emitting the event, to prevent double-firing.\n   */\n  emit(\n    ev: Event,\n    ...args: Events[Event]\n  ): boolean {\n    const data = args[0]\n    // error and close are only events allowed after calling destroy()\n    if (\n      ev !== 'error' &&\n      ev !== 'close' &&\n      ev !== DESTROYED &&\n      this[DESTROYED]\n    ) {\n      return false\n    } else if (ev === 'data') {\n      return !this[OBJECTMODE] && !data\n        ? false\n        : this[ASYNC]\n        ? (defer(() => this[EMITDATA](data as RType)), true)\n        : this[EMITDATA](data as RType)\n    } else if (ev === 'end') {\n      return this[EMITEND]()\n    } else if (ev === 'close') {\n      this[CLOSED] = true\n      // don't emit close before 'end' and 'finish'\n      if (!this[EMITTED_END] && !this[DESTROYED]) return false\n      const ret = super.emit('close')\n      this.removeAllListeners('close')\n      return ret\n    } else if (ev === 'error') {\n      this[EMITTED_ERROR] = data\n      super.emit(ERROR, data)\n      const ret =\n        !this[SIGNAL] || this.listeners('error').length\n          ? super.emit('error', data)\n          : false\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'resume') {\n      const ret = super.emit('resume')\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'finish' || ev === 'prefinish') {\n      const ret = super.emit(ev)\n      this.removeAllListeners(ev)\n      return ret\n    }\n\n    // Some other unknown event\n    const ret = super.emit(ev as string, ...args)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITDATA](data: RType) {\n    for (const p of this[PIPES]) {\n      if (p.dest.write(data as RType) === false) this.pause()\n    }\n    const ret = this[DISCARDED] ? false : super.emit('data', data)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITEND]() {\n    if (this[EMITTED_END]) return false\n\n    this[EMITTED_END] = true\n    this.readable = false\n    return this[ASYNC]\n      ? (defer(() => this[EMITEND2]()), true)\n      : this[EMITEND2]()\n  }\n\n  [EMITEND2]() {\n    if (this[DECODER]) {\n      const data = this[DECODER].end()\n      if (data) {\n        for (const p of this[PIPES]) {\n          p.dest.write(data as RType)\n        }\n        if (!this[DISCARDED]) super.emit('data', data)\n      }\n    }\n\n    for (const p of this[PIPES]) {\n      p.end()\n    }\n    const ret = super.emit('end')\n    this.removeAllListeners('end')\n    return ret\n  }\n\n  /**\n   * Return a Promise that resolves to an array of all emitted data once\n   * the stream ends.\n   */\n  async collect(): Promise {\n    const buf: RType[] & { dataLength: number } = Object.assign([], {\n      dataLength: 0,\n    })\n    if (!this[OBJECTMODE]) buf.dataLength = 0\n    // set the promise first, in case an error is raised\n    // by triggering the flow here.\n    const p = this.promise()\n    this.on('data', c => {\n      buf.push(c)\n      if (!this[OBJECTMODE])\n        buf.dataLength += (c as Minipass.BufferOrString).length\n    })\n    await p\n    return buf\n  }\n\n  /**\n   * Return a Promise that resolves to the concatenation of all emitted data\n   * once the stream ends.\n   *\n   * Not allowed on objectMode streams.\n   */\n  async concat(): Promise {\n    if (this[OBJECTMODE]) {\n      throw new Error('cannot concat in objectMode')\n    }\n    const buf = await this.collect()\n    return (\n      this[ENCODING]\n        ? buf.join('')\n        : Buffer.concat(buf as Buffer[], buf.dataLength)\n    ) as RType\n  }\n\n  /**\n   * Return a void Promise that resolves once the stream ends.\n   */\n  async promise(): Promise {\n    return new Promise((resolve, reject) => {\n      this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n      this.on('error', er => reject(er))\n      this.on('end', () => resolve())\n    })\n  }\n\n  /**\n   * Asynchronous `for await of` iteration.\n   *\n   * This will continue emitting all chunks until the stream terminates.\n   */\n  [Symbol.asyncIterator](): AsyncGenerator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = async (): Promise> => {\n      this.pause()\n      stopped = true\n      return { value: undefined, done: true }\n    }\n    const next = (): Promise> => {\n      if (stopped) return stop()\n      const res = this.read()\n      if (res !== null) return Promise.resolve({ done: false, value: res })\n\n      if (this[EOF]) return stop()\n\n      let resolve!: (res: IteratorResult) => void\n      let reject!: (er: unknown) => void\n      const onerr = (er: unknown) => {\n        this.off('data', ondata)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        reject(er)\n      }\n      const ondata = (value: RType) => {\n        this.off('error', onerr)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        this.pause()\n        resolve({ value, done: !!this[EOF] })\n      }\n      const onend = () => {\n        this.off('error', onerr)\n        this.off('data', ondata)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        resolve({ done: true, value: undefined })\n      }\n      const ondestroy = () => onerr(new Error('stream destroyed'))\n      return new Promise>((res, rej) => {\n        reject = rej\n        resolve = res\n        this.once(DESTROYED, ondestroy)\n        this.once('error', onerr)\n        this.once('end', onend)\n        this.once('data', ondata)\n      })\n    }\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.asyncIterator]() {\n        return this\n      },\n      [Symbol.asyncDispose]: async () => {},\n    }\n  }\n\n  /**\n   * Synchronous `for of` iteration.\n   *\n   * The iteration will terminate when the internal buffer runs out, even\n   * if the stream has not yet terminated.\n   */\n  [Symbol.iterator](): Generator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = (): IteratorReturnResult => {\n      this.pause()\n      this.off(ERROR, stop)\n      this.off(DESTROYED, stop)\n      this.off('end', stop)\n      stopped = true\n      return { done: true, value: undefined }\n    }\n\n    const next = (): IteratorResult => {\n      if (stopped) return stop()\n      const value = this.read()\n      return value === null ? stop() : { done: false, value }\n    }\n\n    this.once('end', stop)\n    this.once(ERROR, stop)\n    this.once(DESTROYED, stop)\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.iterator]() {\n        return this\n      },\n      [Symbol.dispose]: () => {},\n    }\n  }\n\n  /**\n   * Destroy a stream, preventing it from being used for any further purpose.\n   *\n   * If the stream has a `close()` method, then it will be called on\n   * destruction.\n   *\n   * After destruction, any attempt to write data, read data, or emit most\n   * events will be ignored.\n   *\n   * If an error argument is provided, then it will be emitted in an\n   * 'error' event.\n   */\n  destroy(er?: unknown) {\n    if (this[DESTROYED]) {\n      if (er) this.emit('error', er)\n      else this.emit(DESTROYED)\n      return this\n    }\n\n    this[DESTROYED] = true\n    this[DISCARDED] = true\n\n    // throw away all buffered data, it's never coming out\n    this[BUFFER].length = 0\n    this[BUFFERLENGTH] = 0\n\n    const wc = this as Minipass & {\n      close?: () => void\n    }\n    if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n    if (er) this.emit('error', er)\n    // if no error to emit, still reject pending promises\n    else this.emit(DESTROYED)\n\n    return this\n  }\n\n  /**\n   * Alias for {@link isStream}\n   *\n   * Former export location, maintained for backwards compatibility.\n   *\n   * @deprecated\n   */\n  static get isStream() {\n    return isStream\n  }\n}\n", "// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\nconst customInspect = Symbol.for('nodejs.util.inspect.custom')\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  [customInspect]() {\n    return 'Pattern <' + this.#globList.slice(this.#index).join('/') + '>'\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n", "// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      platform = defaultPlatform,\n    }: GlobWalkerOpts,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    this.mmopts = {\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n    }\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const m = new Minimatch(p.globString(), this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = p.fullpath() + '/'\n    const relative = (p.relative() || '.') + '/'\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n", "// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n", "/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Set\n  : O extends GWOFileTypesFalse ? Set\n  : O extends GWOFileTypesUnset ? Set\n  : Set\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts)\n  : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n          '.' + this.#sep\n        : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  matches = new Set>()\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise>> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Set> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n", "import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  if (!Array.isArray(pattern)) {\n    pattern = [pattern]\n  }\n  for (const p of pattern) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n", "import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n"],
-  "mappings": "AAAO,IAAMA,GAAW,CACtBC,EACAC,EACAC,IACE,CACF,IAAMC,EAAKH,aAAa,OAASI,GAAWJ,EAAGE,CAAG,EAAIF,EAChDK,EAAKJ,aAAa,OAASG,GAAWH,EAAGC,CAAG,EAAID,EAEhD,EAAIE,IAAO,MAAQE,GAAM,MAAQC,GAAMH,EAAIE,EAAIH,CAAG,EAExD,OACE,GAAK,CACH,MAAO,EAAE,CAAC,EACV,IAAK,EAAE,CAAC,EACR,IAAKA,EAAI,MAAM,EAAG,EAAE,CAAC,CAAC,EACtB,KAAMA,EAAI,MAAM,EAAE,CAAC,EAAIC,EAAG,OAAQ,EAAE,CAAC,CAAC,EACtC,KAAMD,EAAI,MAAM,EAAE,CAAC,EAAIG,EAAG,MAAM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AAQ,GACA,WAAAT,GACA,OAAAM,GACA,eAAAV,GACA,WAAAS,GACA,YAAAD,GACA,QAAAI,GACA,gBAAAL,GACA,YAAAI,GACA,KAAAR,EACA,SAAAY,GACA,OAAAC,GACA,SAAAC,EACD,EACDH,GAAK,KAAOA",
-  "names": ["balanced", "a", "b", "str", "ma", "maybeMatch", "mb", "range", "reg", "m", "begs", "beg", "left", "right", "result", "ai", "bi", "i", "r", "escSlash", "escOpen", "escClose", "escComma", "escPeriod", "escSlashPattern", "escOpenPattern", "escClosePattern", "escCommaPattern", "escPeriodPattern", "slashPattern", "openPattern", "closePattern", "commaPattern", "periodPattern", "EXPANSION_MAX", "numeric", "str", "escapeBraces", "unescapeBraces", "parseCommaParts", "parts", "m", "balanced", "pre", "body", "post", "p", "postParts", "expand", "options", "max", "expand_", "embrace", "isPadded", "el", "lte", "i", "y", "gte", "isTop", "expansions", "k", "expansion", "isNumericSequence", "isAlphaSequence", "isSequence", "isOptions", "n", "N", "x", "width", "incr", "test", "pad", "c", "need", "z", "j", "assertValidPattern", "pattern", "posixClasses", "braceEscape", "s", "regexpEscape", "rangesToString", "ranges", "parseClass", "glob", "position", "pos", "negs", "i", "sawStart", "uflag", "escaping", "negate", "endPos", "rangeStart", "WHILE", "c", "cls", "unip", "u", "neg", "r", "sranges", "snegs", "unescape", "s", "windowsPathsNoEscape", "magicalBraces", "types", "isExtglobType", "c", "startNoTraversal", "startNoDot", "addPatternStart", "justDots", "reSpecials", "regExpEscape", "s", "qmark", "star", "starNoEmpty", "AST", "_AST", "#root", "#hasMagic", "#uflag", "#parts", "#parent", "#parentIndex", "#negs", "#filledNegs", "#options", "#toString", "#emptyExt", "type", "parent", "options", "p", "#fillNegs", "n", "pp", "part", "parts", "ret", "i", "pl", "#parseAST", "str", "ast", "pos", "opt", "escaping", "inBrace", "braceStart", "braceNeg", "acc", "ext", "pattern", "glob", "re", "body", "hasMagic", "uflag", "flags", "allowDot", "dot", "noEmpty", "src", "_", "#parseGlob", "start", "aps", "needNoTrav", "needNoDot", "end", "unescape", "repeated", "#partsToRegExp", "bodyDotAllowed", "final", "close", "_hasMagic", "inStar", "needUflag", "consumed", "magic", "parseClass", "escape", "s", "windowsPathsNoEscape", "magicalBraces", "minimatch", "p", "pattern", "options", "assertValidPattern", "Minimatch", "starDotExtRE", "starDotExtTest", "ext", "f", "starDotExtTestDot", "starDotExtTestNocase", "starDotExtTestNocaseDot", "starDotStarRE", "starDotStarTest", "starDotStarTestDot", "dotStarRE", "dotStarTest", "starRE", "starTest", "starTestDot", "qmarksRE", "qmarksTestNocase", "$0", "noext", "qmarksTestNoExt", "qmarksTestNocaseDot", "qmarksTestNoExtDot", "qmarksTestDot", "qmarksTest", "len", "defaultPlatform", "path", "sep", "GLOBSTAR", "qmark", "star", "twoStarDot", "twoStarNoDot", "filter", "a", "b", "defaults", "def", "orig", "type", "parent", "list", "braceExpand", "expand", "makeRe", "match", "mm", "globMagic", "regExpEscape", "s", "awe", "part", "_", "args", "rawGlobParts", "set", "__", "isUNC", "isDrive", "ss", "i", "globParts", "j", "optimizationLevel", "parts", "gs", "prev", "didSomething", "dd", "gss", "next", "p2", "other", "splin", "matched", "emptyGSMatch", "ai", "bi", "result", "which", "negate", "negateOffset", "file", "partial", "fileDrive", "fileUNC", "patternDrive", "patternUNC", "fdi", "pdi", "fd", "pd", "fi", "pi", "fl", "pl", "fr", "pr", "swallowee", "hit", "m", "fastTest", "re", "AST", "twoStar", "flags", "pp", "filtered", "prefixes", "open", "close", "ff", "filename", "escape", "unescape", "fileURLToPath", "defaultPerf", "warned", "PROCESS", "emitWarning", "msg", "type", "code", "fn", "AC", "AS", "_", "warnACPolyfill", "reason", "printACPolyfillWarning", "shouldWarn", "isPosInt", "n", "getUintArray", "max", "ZeroArray", "size", "Stack", "_Stack", "#constructing", "HeapCls", "s", "LRUCache", "_LRUCache", "#max", "#maxSize", "#dispose", "#onInsert", "#disposeAfter", "#fetchMethod", "#memoMethod", "#perf", "#size", "#calculatedSize", "#keyMap", "#keyList", "#valList", "#next", "#prev", "#head", "#tail", "#free", "#disposed", "#sizes", "#starts", "#ttls", "#autopurgeTimers", "#hasDispose", "#hasFetchMethod", "#hasDisposeAfter", "#hasOnInsert", "c", "p", "#isBackgroundFetch", "k", "index", "options", "context", "#backgroundFetch", "#moveToTail", "#indexes", "#rindexes", "#isStale", "ttl", "ttlResolution", "ttlAutopurge", "updateAgeOnGet", "updateAgeOnHas", "allowStale", "dispose", "onInsert", "disposeAfter", "noDisposeOnSet", "noUpdateTTL", "maxSize", "maxEntrySize", "sizeCalculation", "fetchMethod", "memoMethod", "noDeleteOnFetchRejection", "noDeleteOnStaleGet", "allowStaleOnFetchRejection", "allowStaleOnFetchAbort", "ignoreFetchAbort", "perf", "defaultPerf", "UintArray", "#initializeSizeTracking", "#initializeTTLTracking", "code", "shouldWarn", "warned", "emitWarning", "key", "ttls", "starts", "purgeTimers", "#setItemTTL", "start", "t", "#delete", "#updateItemAge", "#statusTTL", "status", "cachedNow", "getNow", "age", "sizes", "#removeItemSize", "#requireSize", "v", "#addItemSize", "#evict", "_i", "_s", "_st", "_k", "_v", "i", "#isValidIndex", "fn", "getOptions", "value", "thisp", "deleted", "entry", "remain", "arr", "setOptions", "oldVal", "oldValue", "dt", "task", "val", "free", "head", "hasOptions", "peekOptions", "ac", "AC", "signal", "fetchOpts", "cb", "updateCache", "aborted", "ignoreAbort", "proceed", "fetchFail", "bf", "vl", "eb", "er", "allowStaleAborted", "noDelete", "pcall", "res", "rej", "fmp", "b", "fetchOptions", "forceRefresh", "stale", "isStale", "staleVal", "memoOptions", "vv", "fetching", "#connect", "reason", "#clear", "pi", "ni", "posix", "win32", "fileURLToPath", "lstatSync", "readdirCB", "readdirSync", "readlinkSync", "rps", "actualFS", "lstat", "readdir", "readlink", "realpath", "EventEmitter", "Stream", "StringDecoder", "proc", "isStream", "s", "Minipass", "isReadable", "isWritable", "EOF", "MAYBE_EMIT_END", "EMITTED_END", "EMITTING_END", "EMITTED_ERROR", "CLOSED", "READ", "FLUSH", "FLUSHCHUNK", "ENCODING", "DECODER", "FLOWING", "PAUSED", "RESUME", "BUFFER", "PIPES", "BUFFERLENGTH", "BUFFERPUSH", "BUFFERSHIFT", "OBJECTMODE", "DESTROYED", "ERROR", "EMITDATA", "EMITEND", "EMITEND2", "ASYNC", "ABORT", "ABORTED", "SIGNAL", "DATALISTENERS", "DISCARDED", "defer", "fn", "nodefer", "isEndish", "ev", "isArrayBufferLike", "b", "isArrayBufferView", "Pipe", "src", "dest", "opts", "_er", "PipeProxyErrors", "er", "isObjectModeOptions", "o", "isEncodingOptions", "args", "options", "signal", "_enc", "_om", "a", "_", "chunk", "encoding", "cb", "n", "ret", "c", "noDrain", "ended", "p", "handler", "h", "data", "buf", "resolve", "reject", "stopped", "stop", "res", "onerr", "ondata", "onend", "ondestroy", "value", "rej", "next", "wc", "realpathSync", "rps", "defaultFS", "lstatSync", "readdirCB", "readdirSync", "readlinkSync", "lstat", "readdir", "readlink", "realpath", "fsFromOption", "fsOption", "actualFS", "uncDriveRegexp", "uncToDrive", "rootPath", "eitherSep", "UNKNOWN", "IFIFO", "IFCHR", "IFDIR", "IFBLK", "IFREG", "IFLNK", "IFSOCK", "IFMT", "IFMT_UNKNOWN", "READDIR_CALLED", "LSTAT_CALLED", "ENOTDIR", "ENOENT", "ENOREADLINK", "ENOREALPATH", "ENOCHILD", "TYPEMASK", "entToType", "s", "normalizeCache", "L", "normalize", "c", "n", "normalizeNocaseCache", "normalizeNocase", "ResolveCache", "ChildrenCache", "maxSize", "a", "setAsCwd", "PathBase", "#fs", "#dev", "#mode", "#nlink", "#uid", "#gid", "#rdev", "#blksize", "#ino", "#size", "#blocks", "#atimeMs", "#mtimeMs", "#ctimeMs", "#birthtimeMs", "#atime", "#mtime", "#ctime", "#birthtime", "#matchName", "#depth", "#fullpath", "#fullpathPosix", "#relative", "#relativePosix", "#type", "#children", "#linkTarget", "#realpath", "name", "type", "root", "roots", "nocase", "children", "opts", "path", "dirParts", "#resolveParts", "p", "part", "cached", "pathPart", "fullpath", "pchild", "pv", "fp", "pfpp", "fpp", "ifmt", "target", "read", "linkTarget", "er", "#readlinkFail", "#readdirSuccess", "#markENOENT", "#markChildrenENOENT", "#markENOREALPATH", "#markENOTDIR", "#readdirFail", "code", "#lstatFail", "ter", "#readdirAddChild", "e", "#readdirMaybePromoteChild", "#readdirAddNewChild", "child", "#readdirPromoteChild", "index", "v", "#applyStat", "st", "atime", "atimeMs", "birthtime", "birthtimeMs", "blksize", "blocks", "ctime", "ctimeMs", "dev", "gid", "ino", "mode", "mtime", "mtimeMs", "nlink", "rdev", "size", "uid", "#onReaddirCB", "#readdirCBInFlight", "#callOnReaddirCB", "cbs", "cb", "allowZalgo", "entries", "#asyncReaddirInFlight", "resolve", "res", "dirs", "walkFilter", "rp", "oldCwd", "changed", "PathWin32", "_PathWin32", "win32", "compare", "PathScurryWin32", "PathPosix", "_PathPosix", "_rootPath", "PathScurryBase", "#resolveCache", "#resolvePosixCache", "cwd", "pathImpl", "sep", "childrenCacheSize", "fs", "fileURLToPath", "cwdPath", "split", "prev", "len", "joinSep", "abs", "sawFirst", "l", "paths", "r", "i", "result", "entry", "withFileTypes", "follow", "filter", "results", "walk", "dir", "next", "start", "rej", "options", "Minipass", "queue", "processing", "process", "paused", "onReaddir", "didRealpaths", "promises", "sync", "PathScurryPosix", "posix", "_dir", "PathScurryDarwin", "Path", "PathScurry", "isPatternList", "pl", "isGlobList", "gl", "customInspect", "Pattern", "_Pattern", "#patternList", "#globList", "#index", "#platform", "#rest", "#globString", "#isDrive", "#isUNC", "#isAbsolute", "#followGlobstar", "patternList", "globList", "index", "platform", "p0", "p1", "p2", "p3", "prest", "g0", "g1", "g2", "g3", "grest", "g", "p", "GLOBSTAR", "defaultPlatform", "Ignore", "ignored", "nobrace", "nocase", "noext", "noglobstar", "platform", "ign", "mm", "Minimatch", "i", "parsed", "globParts", "p", "Pattern", "m", "children", "absolute", "fullpath", "fullpaths", "relative", "relatives", "HasWalkedCache", "_HasWalkedCache", "store", "target", "pattern", "fullpath", "cached", "MatchRecord", "absolute", "ifDir", "n", "current", "path", "SubWalks", "subs", "p", "k", "Processor", "_Processor", "opts", "hasWalkedCache", "patterns", "processingSet", "t", "root", "rest", "changed", "GLOBSTAR", "rp", "rrest", "tp", "parent", "entries", "results", "e", "ep", "makeIgnore", "ignore", "opts", "Ignore", "GlobUtil", "#onResume", "#ignore", "#sep", "patterns", "path", "m", "#ignored", "#childrenIgnored", "fn", "e", "ifDir", "rpc", "s", "target", "absolute", "ign", "abs", "mark", "rel", "pre", "p", "cb", "Processor", "processor", "tasks", "next", "t", "childrenCached", "_", "entries", "children", "GlobWalker", "res", "rej", "GlobStream", "Minipass", "defaultPlatform", "Glob", "pattern", "opts", "fileURLToPath", "p", "Scurry", "PathScurryWin32", "PathScurryDarwin", "PathScurryPosix", "PathScurry", "nocaseMagicOnly", "mmo", "mms", "Minimatch", "matchSet", "globParts", "set", "m", "i", "g", "Pattern", "GlobWalker", "GlobStream", "hasMagic", "pattern", "options", "p", "Minimatch", "globStreamSync", "pattern", "options", "Glob", "globStream", "globSync", "glob_", "globIterateSync", "globIterate", "streamSync", "stream", "iterateSync", "iterate", "sync", "glob", "hasMagic", "escape", "unescape"]
+  "sources": ["../../node_modules/balanced-match/src/index.ts", "../../node_modules/brace-expansion/src/index.ts", "../../node_modules/@isaacs/nonrecursive-glob-match/src/numeric-range.ts", "../../node_modules/@isaacs/nonrecursive-glob-match/src/parse-class.ts", "../../node_modules/@isaacs/nonrecursive-glob-match/src/index.ts", "../../node_modules/minimatch/src/assert-valid-pattern.ts", "../../node_modules/minimatch/src/escape.ts", "../../node_modules/minimatch/src/unescape.ts", "../../node_modules/minimatch/src/index.ts", "../../src/glob.ts", "../../node_modules/lru-cache/src/diagnostics-channel-node.ts", "../../node_modules/lru-cache/src/perf.ts", "../../node_modules/lru-cache/src/index.ts", "../../node_modules/path-scurry/src/index.ts", "../../node_modules/minipass/src/index.ts", "../../src/pattern.ts", "../../src/ignore.ts", "../../src/processor.ts", "../../src/walker.ts", "../../src/has-magic.ts", "../../src/index.ts"],
+  "sourcesContent": ["export const balanced = (\n  a: string | RegExp,\n  b: string | RegExp,\n  str: string,\n) => {\n  const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n  const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n  const r = ma !== null && mb != null && range(ma, mb, str)\n\n  return (\n    r && {\n      start: r[0],\n      end: r[1],\n      pre: str.slice(0, r[0]),\n      body: str.slice(r[0] + ma.length, r[1]),\n      post: str.slice(r[1] + mb.length),\n    }\n  )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n  const m = str.match(reg)\n  return m ? m[0] : null\n}\n\nexport const range = (\n  a: string,\n  b: string,\n  str: string,\n): undefined | [number, number] => {\n  let begs: number[],\n    beg: number | undefined,\n    left: number,\n    right: number | undefined = undefined,\n    result: undefined | [number, number]\n  let ai = str.indexOf(a)\n  let bi = str.indexOf(b, ai + 1)\n  let i = ai\n\n  if (ai >= 0 && bi > 0) {\n    if (a === b) {\n      return [ai, bi]\n    }\n    begs = []\n    left = str.length\n\n    while (i >= 0 && !result) {\n      if (i === ai) {\n        begs.push(i)\n        ai = str.indexOf(a, i + 1)\n      } else if (begs.length === 1) {\n        const r = begs.pop()\n        if (r !== undefined) result = [r, bi]\n      } else {\n        beg = begs.pop()\n        if (beg !== undefined && beg < left) {\n          left = beg\n          right = bi\n        }\n\n        bi = str.indexOf(b, i + 1)\n      }\n\n      i = ai < bi && ai >= 0 ? ai : bi\n    }\n\n    if (begs.length && right !== undefined) {\n      result = [left, right]\n    }\n  }\n\n  return result\n}\n", "import { balanced } from 'balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\\\./g\n\nexport const EXPANSION_MAX = 100_000\n\n// `EXPANSION_MAX` caps the *number* of expansions, but not their length. An\n// input like `'{a,b}'.repeat(1500)` stays under that count - its output is\n// truncated to 100k results - while making every result ~1500 characters\n// long. The result set, and the intermediate arrays built while combining\n// brace sets, then grow large enough to exhaust memory and crash the process\n// (CVE-2026-14257). `EXPANSION_MAX_LENGTH` bounds the total number of\n// characters the accumulator may hold at any point, so memory stays flat no\n// matter how many brace groups are chained. The limit sits well above any\n// realistic expansion (100k results hitting `EXPANSION_MAX` measure ~1M\n// characters) so legitimate input is unaffected.\nexport const EXPANSION_MAX_LENGTH = 4_000_000\n\n// `expand_` recurses once per level of brace *nesting* - both when expanding a\n// set's comma members and when re-wrapping a set whose body is a single part.\n// The CVE-2026-14257 fix made the *tail* iterative (recursion on `m.post`, one\n// level per chained group), which left nesting depth unbounded: about 3,100\n// levels of `{{{...a,b...}}}` - only ~6KB of input - exhausted the native stack\n// and crashed the process. `EXPANSION_MAX_DEPTH` bounds how deep the parser\n// will follow nesting. It sits far above any realistic pattern and well below\n// the depth at which the stack runs out.\nexport const EXPANSION_MAX_DEPTH = 1_000\n\n// Bash keeps a quirk where a brace group followed by a comma set still expands\n// (`{a},b}`). The parser implements it by rewriting the string and restarting\n// the scan, absorbing one `}` per pass. `n` trailing braces therefore cost `n`\n// full passes over a string that itself grows by one `escClose` sentinel each\n// time - quadratic in `n`, with a ~26x constant from the sentinel's length.\n// 128KB of `'{a}' + '}'.repeat(n) + ',z}'` blocked the event loop for 27\n// seconds to produce two results. `EXPANSION_MAX_REWRITES` bounds how many\n// times the scan may restart. Real `{a},b}` input needs a handful.\nexport const EXPANSION_MAX_REWRITES = 1_000\n\nfunction numeric(str: string) {\n  return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n  return str\n    .replace(slashPattern, escSlash)\n    .replace(openPattern, escOpen)\n    .replace(closePattern, escClose)\n    .replace(commaPattern, escComma)\n    .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n  return str\n    .replace(escSlashPattern, '\\\\')\n    .replace(escOpenPattern, '{')\n    .replace(escClosePattern, '}')\n    .replace(escCommaPattern, ',')\n    .replace(escPeriodPattern, '.')\n}\n\n// Like `target.push(...items)` but doesn't overflow the stack\nfunction pushAll(target: string[], items: string[]) {\n  for (let i = 0; i < items.length; i++) {\n    target.push(items[i] as string)\n  }\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n  const parts: string[] = []\n\n  // Walk the brace groups iteratively. Recursing on `post` once per group let a\n  // chain of them exhaust the stack - the parsing-side counterpart to\n  // the `expand_` overflow fixed for CVE-2026-14257, and not something `max` or\n  // `maxLength` can bound, since it happens before expansion.\n  //\n  // The part the next chunk continues\n  let carry = ''\n\n  for (;;) {\n    const m = balanced('{', '}', str)\n\n    if (!m) {\n      const tail = str.split(',')\n      tail[0] = carry + (tail[0] as string)\n      pushAll(parts, tail)\n      return parts\n    }\n\n    const { pre, body, post } = m\n    const p = pre.split(',')\n    p[0] = carry + (p[0] as string)\n    p[p.length - 1] += '{' + body + '}'\n\n    if (!post.length) {\n      pushAll(parts, p)\n      return parts\n    }\n\n    carry = p.pop() as string\n    pushAll(parts, p)\n    str = post\n  }\n}\n\nexport type BraceExpansionOptions = {\n  max?: number\n  maxLength?: number\n  maxDepth?: number\n  maxRewrites?: number\n}\n\nexport function expand(str: string, options: BraceExpansionOptions = {}) {\n  if (!str) {\n    return []\n  }\n\n  const {\n    max = EXPANSION_MAX,\n    maxLength = EXPANSION_MAX_LENGTH,\n    maxDepth = EXPANSION_MAX_DEPTH,\n    maxRewrites = EXPANSION_MAX_REWRITES,\n  } = options\n\n  // I don't know why Bash 4.3 does this, but it does.\n  // Anything starting with {} will have the first two bytes preserved\n  // but *only* at the top level, so {},a}b will not expand to anything,\n  // but a{},b}c will be expanded to [a}c,abc].\n  // One could argue that this is a bug in Bash, but since the goal of\n  // this module is to match Bash's rules, we escape a leading {}\n  if (str.slice(0, 2) === '{}') {\n    str = '\\\\{\\\\}' + str.slice(2)\n  }\n\n  return expand_(\n    escapeBraces(str),\n    max,\n    maxLength,\n    maxDepth,\n    0,\n    maxRewrites,\n    true,\n  ).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n  return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n  return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n  return i <= y\n}\n\nfunction gte(i: number, y: number) {\n  return i >= y\n}\n\n// Build `{ acc[a] + pre + values[v] }` for every combination, capping the\n// number of results at `max` and the total number of characters at `maxLength`.\n// This is the one place output grows, so bounding it here keeps the single\n// accumulator - and therefore memory - flat regardless of how many brace groups\n// are combined (CVE-2026-14257).\nfunction combine(\n  acc: string[],\n  pre: string,\n  values: string[],\n  max: number,\n  maxLength: number,\n  dropEmpties: boolean,\n): string[] {\n  const out: string[] = []\n  let length = 0\n  for (let a = 0; a < acc.length; a++) {\n    for (let v = 0; v < values.length; v++) {\n      if (out.length >= max) return out\n      const expansion = (acc[a] as string) + pre + values[v]\n      // Bash drops empty results at the top level. Skip them before they count\n      // against `max`, so `max` bounds the number of *kept* results.\n      if (dropEmpties && !expansion) continue\n      if (length + expansion.length > maxLength) return out\n      out.push(expansion)\n      length += expansion.length\n    }\n  }\n  return out\n}\n\n// The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)\n// sequence body.\nfunction expandSequence(\n  body: string,\n  isAlphaSequence: boolean,\n  max: number,\n  maxLength: number,\n): string[] {\n  const n = body.split(/\\.\\./)\n  const N: string[] = []\n  // A sequence body always splits into two or three parts, but the compiler\n  // can't know that.\n  /* c8 ignore start */\n  if (n[0] === undefined || n[1] === undefined) {\n    return N\n  }\n  /* c8 ignore stop */\n  const x = numeric(n[0])\n  const y = numeric(n[1])\n  const width = Math.max(n[0].length, n[1].length)\n  let incr =\n    n.length === 3 && n[2] !== undefined ?\n      Math.max(Math.abs(numeric(n[2])), 1)\n    : 1\n  let test = lte\n  const reverse = y < x\n  if (reverse) {\n    incr *= -1\n    test = gte\n  }\n  const pad = n.some(isPadded)\n\n  let length = 0\n  for (let i = x; test(i, y) && N.length < max; i += incr) {\n    let c\n    if (isAlphaSequence) {\n      c = String.fromCharCode(i)\n      if (c === '\\\\') {\n        c = ''\n      }\n    } else {\n      c = String(i)\n      if (pad) {\n        const need = width - c.length\n        if (need > 0) {\n          const z = new Array(need + 1).join('0')\n          if (i < 0) {\n            c = '-' + z + c.slice(1)\n          } else {\n            c = z + c\n          }\n        }\n      }\n    }\n    if (length + c.length > maxLength) break\n    N.push(c)\n    length += c.length\n  }\n  return N\n}\n\nfunction expand_(\n  str: string,\n  max: number,\n  maxLength: number,\n  maxDepth: number,\n  depth: number,\n  maxRewrites: number,\n  isTop: boolean,\n): string[] {\n  // Too deeply nested to keep following: treat the rest as literal, the same\n  // way a group that cannot expand is already handled. Truncating rather than\n  // throwing keeps `expand` total, matching `max` and `maxLength`.\n  if (depth > maxDepth) {\n    return [str]\n  }\n\n  // Consume the string's top-level brace groups left to right, threading a\n  // running set of combined prefixes (`acc`). Expanding the tail iteratively -\n  // rather than recursing on `m.post` once per group - keeps the native stack\n  // depth constant, so deeply chained input (`'{a,b}'.repeat(3000)`) can no\n  // longer overflow the stack, and leaves a single accumulator whose size\n  // `maxLength` bounds directly (CVE-2026-14257).\n  let acc: string[] = ['']\n\n  // Bash drops empty results, but only when the *first* top-level group is a\n  // comma set - a sequence like `{a..\\}` may legitimately yield ''. The drop\n  // is on the final strings, so it is applied to whichever `combine` produces\n  // them (the one with no brace set left in the tail).\n  // How many times the `{a},b}` rewrite below has restarted the scan. Each pass\n  // re-reads the whole string, so leaving this unbounded is quadratic.\n  let rewrites = 0\n  let dropEmpties = false\n  let firstGroup = true\n\n  for (;;) {\n    const m = balanced('{', '}', str)\n\n    // No brace set left: the rest of the string is literal.\n    if (!m) {\n      return combine(acc, str, [''], max, maxLength, dropEmpties)\n    }\n\n    // no need to expand pre, since it is guaranteed to be free of brace-sets\n    const pre = m.pre\n\n    if (/\\$$/.test(pre)) {\n      acc = combine(\n        acc,\n        pre + '{' + m.body + '}',\n        [''],\n        max,\n        maxLength,\n        dropEmpties && !m.post.length,\n      )\n      firstGroup = false\n      if (!m.post.length) break\n      str = m.post\n      continue\n    }\n\n    const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n    const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(\n      m.body,\n    )\n    const isSequence = isNumericSequence || isAlphaSequence\n    const isOptions = m.body.indexOf(',') >= 0\n    if (!isSequence && !isOptions) {\n      // {a},b}\n      if (rewrites < maxRewrites && m.post.match(/,(?!,).*\\}/)) {\n        rewrites++\n        str = m.pre + '{' + m.body + escClose + m.post\n        isTop = true\n        continue\n      }\n      // Nothing here expands, so the whole remaining string is literal.\n      return combine(\n        acc,\n        pre + '{' + m.body + '}' + m.post,\n        [''],\n        max,\n        maxLength,\n        dropEmpties,\n      )\n    }\n\n    if (firstGroup) {\n      dropEmpties = isTop && !isSequence\n      firstGroup = false\n    }\n\n    let values: string[]\n    if (isSequence) {\n      values = expandSequence(m.body, isAlphaSequence, max, maxLength)\n    } else {\n      let n = parseCommaParts(m.body)\n      if (n.length === 1 && n[0] !== undefined) {\n        // x{{a,b}}y ==> x{a}y x{b}y\n        n = expand_(\n          n[0],\n          max,\n          maxLength,\n          maxDepth,\n          depth + 1,\n          maxRewrites,\n          false,\n        ).map(embrace)\n        //XXX is this necessary? Can't seem to hit it in tests.\n        /* c8 ignore start */\n        if (n.length === 1) {\n          acc = combine(\n            acc,\n            pre + n[0],\n            [''],\n            max,\n            maxLength,\n            dropEmpties && !m.post.length,\n          )\n          if (!m.post.length) break\n          str = m.post\n          continue\n        }\n        /* c8 ignore stop */\n      }\n\n      // Values that `combine` is going to drop as empty produce no result, so\n      // they must not count against `max` - otherwise `{a,,b}` with `max: 2`\n      // would stop at `['a', '']` and yield one result instead of two. Skipping\n      // them outright keeps `values` bounded while leaving `max` a bound on\n      // *kept* results.\n      let dropsEmpties = dropEmpties && !m.post.length && !pre\n      for (let d = 0; dropsEmpties && d < acc.length; d++) {\n        if (acc[d]) {\n          dropsEmpties = false\n        }\n      }\n\n      values = []\n      let valuesLength = 0\n      outer: for (let j = 0; j < n.length; j++) {\n        const expanded = expand_(\n          n[j] as string,\n          max,\n          maxLength,\n          maxDepth,\n          depth + 1,\n          maxRewrites,\n          false,\n        )\n        for (let k = 0; k < expanded.length; k++) {\n          const v = expanded[k] as string\n          if (dropsEmpties && !v) continue\n          if (\n            values.length >= max ||\n            valuesLength + v.length > maxLength\n          ) {\n            break outer\n          }\n          values.push(v)\n          valuesLength += v.length\n        }\n      }\n    }\n\n    acc = combine(\n      acc,\n      pre,\n      values,\n      max,\n      maxLength,\n      dropEmpties && !m.post.length,\n    )\n    if (!m.post.length) break\n    str = m.post\n  }\n\n  return acc\n}\n", "import type { Item } from './index.js'\n\n// One digit, or a class of digits from a to b.\nconst digit = (a: number, b: number): Item =>\n  a === b ?\n    { t: 'lit', ch: String(a) }\n  : { t: 'class', re: new RegExp(`^[${a}-${b}]$`) }\n\nconst prefix = (d: number, alts: Item[][]) =>\n  alts.map(s => [digit(d, d), ...s])\n\n// The digit strings from a to b, which have the same length.\nconst fixed = (a: string, b: string): Item[][] => {\n  if (!a) return [[]]\n  let lo = +a[0]!\n  let hi = +b[0]!\n  const ra = a.slice(1)\n  const rb = b.slice(1)\n  if (lo === hi) return prefix(lo, fixed(ra, rb))\n  const zeros = '0'.repeat(ra.length)\n  const nines = '9'.repeat(ra.length)\n  const out: Item[][] = []\n  if (ra !== zeros) out.push(...prefix(lo++, fixed(ra, nines)))\n  const last = rb === nines ? [] : prefix(hi--, fixed(zeros, rb))\n  if (lo <= hi) {\n    out.push([digit(lo, hi), ...Array.from(ra, () => digit(0, 9))])\n  }\n  out.push(...last)\n  return out\n}\n\n// The numbers from a to b, where 0 <= a <= b. If width is set, each\n// one has leading zeros to make it that many digits.\nconst nonneg = (a: number, b: number, width: number): Item[][] => {\n  if (width) {\n    return fixed(\n      String(a).padStart(width, '0'),\n      String(b).padStart(width, '0'),\n    )\n  }\n  const out: Item[][] = []\n  for (let len = String(a).length; len <= String(b).length; len++) {\n    const lo = Math.max(a, len === 1 ? 0 : 10 ** (len - 1))\n    const hi = Math.min(b, 10 ** len - 1)\n    out.push(...fixed(String(lo), String(hi)))\n  }\n  return out\n}\n\n/**\n * The strings that the bash brace expansion `{lo..hi}` makes, as\n * the alternatives of an `@(...)` extglob. Each one is a sequence of\n * digits and digit classes, so there are only a few of them, even for\n * a large range.\n *\n * If either end has a leading zero, such as `{01..10}`, each number\n * has leading zeros to make it as long as the longer end, counting a\n * `-` sign. So `{-05..3}` makes `-05` to `-01`, then `000` to `003`.\n *\n * Returns undefined if either end is not a safe integer.\n */\nexport const numericRange = (\n  loStr: string,\n  hiStr: string,\n): Item[][] | undefined => {\n  let lo = Number(loStr)\n  let hi = Number(hiStr)\n  if (!Number.isSafeInteger(lo) || !Number.isSafeInteger(hi)) return\n  if (lo > hi) [lo, hi] = [hi, lo]\n  const padded = /^-?0\\d/.test(loStr) || /^-?0\\d/.test(hiStr)\n  const width = padded ? Math.max(loStr.length, hiStr.length) : 0\n  const out: Item[][] = []\n  if (lo < 0) {\n    const neg = nonneg(Math.max(-hi, 1), -lo, width && width - 1)\n    out.push(...neg.map(s => [{ t: 'lit', ch: '-' } as Item, ...s]))\n  }\n  if (hi >= 0) out.push(...nonneg(Math.max(lo, 0), hi, width))\n  return out\n}\n", "// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n  '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n  '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n  '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n  '[:blank:]': ['\\\\p{Zs}\\\\t'],\n  '[:cntrl:]': ['\\\\p{Cc}'],\n  '[:digit:]': ['\\\\p{Nd}'],\n  '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n  '[:lower:]': ['\\\\p{Ll}'],\n  '[:print:]': ['\\\\p{C}', true],\n  '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n  '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n  '[:upper:]': ['\\\\p{Lu}'],\n  '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n  '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n  glob: string,\n  position: number,\n  nocase: boolean = false,\n  form?: Form,\n): ParseClassResult => {\n  // normalize one class member, if it stays one code point\n  const norm = (c: string) => {\n    const n = form ? c.normalize(form) : c\n    return [...n].length === 1 ? n : c\n  }\n  const pos = position\n  /* c8 ignore start */\n  if (glob.charAt(pos) !== '[') {\n    throw new Error('not in a brace expression')\n  }\n  /* c8 ignore stop */\n  const ranges: string[] = []\n  const negs: string[] = []\n\n  let i = pos + 1\n  let sawStart = false\n  let escaping = false\n  let negate = false\n  let endPos = pos\n  let rangeStart = ''\n  WHILE: while (i < glob.length) {\n    const c = String.fromCodePoint(glob.codePointAt(i)!)\n    if ((c === '!' || c === '^') && i === pos + 1) {\n      negate = true\n      i++\n      continue\n    }\n\n    if (c === ']' && sawStart && !escaping) {\n      endPos = i + 1\n      break\n    }\n\n    sawStart = true\n    if (c === '\\\\') {\n      if (!escaping) {\n        escaping = true\n        i++\n        continue\n      }\n      // escaped \\ char, fall through and treat like normal char\n    }\n    if (c === '[' && !escaping) {\n      // either a posix class, a collation equivalent, or just a [\n      for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n        if (glob.startsWith(cls, i)) {\n          // invalid, [a-[] is fine, but not [a-[:alpha]]\n          if (rangeStart) {\n            return [noMatch, glob.length - pos]\n          }\n          i += cls.length\n          if (neg) negs.push(unip)\n          else ranges.push(unip)\n          continue WHILE\n        }\n      }\n    }\n\n    // now it's just a normal character, effectively\n    escaping = false\n    const n = norm(c)\n    if (rangeStart) {\n      // throw this range away if it's not valid, but others\n      // can still match.\n      if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n        ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n      } else if (n === rangeStart) {\n        ranges.push(braceEscape(n))\n      }\n      rangeStart = ''\n      i += c.length\n      continue\n    }\n\n    // now might be the start of a range.\n    // can be either c-d or c-] or c] or c] at this point\n    if (glob.startsWith('-]', i + c.length)) {\n      ranges.push(braceEscape(n + '-'))\n      i += c.length + 1\n      continue\n    }\n    if (glob.startsWith('-', i + c.length)) {\n      rangeStart = n\n      i += c.length + 1\n      continue\n    }\n\n    // not the start of a range, just a single character\n    ranges.push(braceEscape(n))\n    i += c.length\n  }\n\n  if (endPos < i) {\n    // didn't see the end of the class, not a valid class,\n    // but might still be valid as a literal match.\n    return [noMatch, 0]\n  }\n\n  // if we got no ranges and no negates, then we have a range that\n  // cannot possibly match anything, and that poisons the whole glob\n  if (!ranges.length && !negs.length) {\n    return [noMatch, glob.length - pos]\n  }\n\n  const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n  const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n  const comb =\n    '^' +\n    (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n    : ranges.length ? sranges\n    : snegs)\n\n  return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n", "import { numericRange } from './numeric-range.js'\nimport { type Form, parseClass } from './parse-class.js'\n\nexport type { Form }\n\nexport type MatcherOptions = {\n  /** perform a case-insensitive match */\n  nocase?: boolean\n  /** do not treat strings starting with `.` specially */\n  dot?: boolean\n  /** do not match extglobs (treat them as normal strings) */\n  noext?: boolean\n  /**\n   * normalize unicode in the pattern and the tested strings, with\n   * this form. `true` means `'NFC'`.\n   */\n  normalize?: boolean | Form\n  /**\n   * A char that marks a numeric range in the pattern, as\n   * `..`, where `lo` and `hi` are integers. It\n   * matches the strings that the bash brace expansion `{..}`\n   * makes, such as `{1..100}` or `{001..100}`, without making each\n   * one. A mark is never escaped by a `\\` before it. Inside a `[...]`\n   * class, a mark is a char of the class.\n   */\n  rangeMark?: string\n}\n\n// parsed pattern items\nexport type Item =\n  | { t: 'lit'; ch: string }\n  | { t: 'any' | 'star' }\n  | { t: 'class'; re: RegExp }\n  | { t: 'ext'; type: string; alts: Item[][] }\n\n// extglob syntax tokens become literals if they are not part of a\n// closed extglob\nexport type Token =\n  Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' }\n\n// state machine nodes\nexport type NegNode = { t: 'neg'; id: number; sub: Node; next: Node }\nexport type SplitNode = { t: 'split'; id: number; out: Node[] }\nexport type Node =\n  | ({ t: 'lit'; id: number; next: Node } & Lit)\n  | { t: 'any' | 'star'; id: number; next: Node }\n  | { t: 'class'; id: number; re: RegExp; next: Node }\n  | SplitNode\n  | NegNode\n  | { t: 'match'; id: number }\n\n// the end of the pattern, or of a negated sub-pattern\nconst MATCH: Node = { t: 'match', id: 0 }\n\nconst extTypes = '!?+*@'\n\nconst lit = (ch: string): Item => ({ t: 'lit', ch })\n\nconst reEscape = (s: string) => s.replace(/[\\\\^$.*+?()[\\]{}|/]/g, '\\\\$&')\n\n// a RegExp that only matches `s`, with unicode case folding\nconst newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu')\n\n// foldRe for one literal char. The same chars are in most patterns,\n// so keep them. A RegExp without the `g` or `y` flag has no state to\n// share.\nconst foldCache = new Map()\nconst foldRe = (ch: string) => {\n  let re = foldCache.get(ch)\n  if (!re) {\n    re = newFoldRe(ch)\n    if (foldCache.size >= 1000) foldCache.clear()\n    foldCache.set(ch, re)\n  }\n  return re\n}\n\n/**\n * A literal char. With `nocase:true`, `re` folds case, and `ascii`\n * holds its results for ASCII chars, by char code: 1 for a match,\n * and 2 for not.\n */\nexport type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array }\n\nconst litMatch = (l: Lit, c: string) => {\n  if (c === l.ch) return true\n  if (!l.re) return false\n  const code = c.charCodeAt(0)\n  if (code >= 128) return l.re.test(c)\n  const ascii = (l.ascii ??= new Uint8Array(128))\n  ascii[code] ||= l.re.test(c) ? 1 : 2\n  return ascii[code] === 1\n}\n\nconst tokenize = (\n  p: string,\n  nocase: boolean,\n  noext: boolean,\n  form?: Form,\n  mark?: string,\n) => {\n  const toks: Token[] = []\n  for (let i = 0; i < p.length;) {\n    const c = String.fromCodePoint(p.codePointAt(i)!)\n    if (mark) {\n      // a \\ before a range would only escape its first char\n      const m = c === '\\\\' && p.startsWith(mark, i + 1) ? 1 : 0\n      if (m || c === mark) {\n        const start = i + m + mark.length\n        const end = p.indexOf(mark, start)\n        const r = /^(-?\\d+)\\.\\.(-?\\d+)$/.exec(p.slice(start, end))\n        const alts = end !== -1 && r && numericRange(r[1]!, r[2]!)\n        if (alts) {\n          toks.push({ t: 'ext', type: '@', alts })\n          i = end + mark.length\n          continue\n        }\n      }\n    }\n    if (c === '\\\\') {\n      // a trailing \\ is a literal \\\n      const e = p.codePointAt(i + 1)\n      const ch = e === undefined ? c : String.fromCodePoint(e)\n      toks.push(lit(ch))\n      i += 1 + ch.length\n      continue\n    }\n    if (c === '[') {\n      const [re, consumed] = parseClass(p, i, nocase, form)\n      if (consumed) {\n        toks.push({ t: 'class', re })\n        i += consumed\n        continue\n      }\n    }\n    if (!noext && extTypes.includes(c) && p[i + 1] === '(') {\n      toks.push({ t: 'open', type: c })\n      i += 2\n      continue\n    }\n    toks.push(\n      !noext && c === '|' ? { t: 'bar' }\n      : !noext && c === ')' ? { t: 'close' }\n      : c === '*' ? { t: 'star' }\n      : c === '?' ? { t: 'any' }\n      : lit(c),\n    )\n    i += c.length\n  }\n  return toks\n}\n\n// map each open token index to the index of its close token\nconst pair = (toks: Token[]) => {\n  const pairs = new Map()\n  const stack: number[] = []\n  toks.forEach((tok, i) => {\n    if (tok.t === 'open') stack.push(i)\n    else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i)\n  })\n  return pairs\n}\n\n// build the alternatives between start and end. An open token that\n// is not closed is never inside a closed extglob, so bar and close\n// tokens are only literal at the top level.\nconst build = (\n  toks: Token[],\n  pairs: Map,\n  start: number,\n  end: number,\n  top: boolean,\n): Item[][] => {\n  let seq: Item[] = []\n  const alts = [seq]\n  for (let i = start; i < end; i++) {\n    const tok = toks[i]!\n    const close = pairs.get(i)\n    if (tok.t === 'open' && close !== undefined) {\n      const sub = build(toks, pairs, i + 1, close, false)\n      seq.push({ t: 'ext', type: tok.type, alts: sub })\n      i = close\n    } else if (tok.t === 'bar' && !top) {\n      alts.push((seq = []))\n    } else if (tok.t === 'open') {\n      seq.push(lit(tok.type), lit('('))\n    } else if (tok.t === 'bar') {\n      seq.push(lit('|'))\n    } else if (tok.t === 'close') {\n      seq.push(lit(')'))\n    } else {\n      seq.push(tok)\n    }\n  }\n  return alts\n}\n\n// normalize each run of literal chars as one string, so that a char\n// and the combining marks after it compose (or decompose) together.\n// Syntax is already parsed, so a char that normalizes to a syntax\n// char (such as full-width `*` in NFKC) stays a literal.\nconst normalize = (items: Item[], form: Form): Item[] => {\n  const out: Item[] = []\n  let run = ''\n  const flush = () => {\n    for (const ch of run.normalize(form)) out.push(lit(ch))\n    run = ''\n  }\n  for (const it of items) {\n    if (it.t === 'lit') {\n      run += it.ch\n      continue\n    }\n    flush()\n    out.push(\n      it.t === 'ext' ?\n        { ...it, alts: it.alts.map(a => normalize(a, form)) }\n      : it,\n    )\n  }\n  flush()\n  return out\n}\n\n// the start node, and the number of node ids. Ids are dense, from 0\n// for the match node.\nconst compile = (\n  items: Item[],\n  nocase: boolean,\n): [start: Node, size: number] => {\n  let id = 1\n  const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out })\n  const seq = (items: Item[], next: Node): Node =>\n    items.reduceRight((next, it) => item(it, next), next)\n  const item = (it: Item, next: Node): Node => {\n    switch (it.t) {\n      case 'lit':\n        const re = nocase ? foldRe(it.ch) : undefined\n        return { t: 'lit', id: id++, ch: it.ch, re, next }\n      case 'any':\n      case 'star':\n        return { t: it.t, id: id++, next }\n      case 'class':\n        return { t: 'class', id: id++, re: it.re, next }\n    }\n    const alts = (next: Node) => it.alts.map(a => seq(a, next))\n    switch (it.type) {\n      case '@':\n        return split(alts(next))\n      case '?':\n        return split([next, ...alts(next)])\n      case '!':\n        return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }\n    }\n    // * and +, loop back after each match\n    const after = split([])\n    const entry = split(alts(after))\n    after.out.push(next, entry)\n    return it.type === '*' ? after : entry\n  }\n  const start = seq(items, MATCH)\n  return [start, id]\n}\n\n// one line per node, in the order that a walk from the start\n// reaches them. Edges point to node ids. The nodes of a negated\n// sub-pattern are indented under their negation.\nconst show = (start: Node): string => {\n  const lines: string[] = []\n  const seen = new Set()\n  const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id))\n  const walk = (n: Node, indent: string) => {\n    if (n.t === 'match' || seen.has(n)) return\n    seen.add(n)\n    const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`)\n    switch (n.t) {\n      case 'split':\n        line(`split -> ${n.out.map(ref).join(', ')}`)\n        for (const o of n.out) walk(o, indent)\n        return\n      case 'neg':\n        line(`!(${ref(n.sub)}) -> ${ref(n.next)}`)\n        walk(n.sub, indent + '  ')\n        return walk(n.next, indent)\n      case 'lit':\n        line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`)\n        break\n      case 'class':\n        line(`${n.re} -> ${ref(n.next)}`)\n        break\n      default:\n        line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`)\n    }\n    walk(n.next, indent)\n  }\n  walk(start, '')\n  return [`start -> ${ref(start)}`, ...lines].join('\\n')\n}\n\n// A thread inside a !(...) negation. It holds the threads of the\n// negated sub-pattern, started where the negation started. The\n// negation matches the chars so far if the sub-pattern does not.\ntype Run = { t: 'run'; neg: NegNode; state: State }\n\n// The threads at one position in the string. Each node thread is\n// only kept once, and runs with the same state are only kept once,\n// so that identical threads merge. The match node is not in\n// `threads`, because it can not step. It sets `match` instead.\nclass State {\n  // set by the Sim, to mark the nodes that this state has\n  gen: number\n  threads: Node[] = []\n  match = false\n  runs: Run[] = []\n  // the sorted ids of the threads, with 0 for a match, once the\n  // state is done\n  ids: number[] = []\n\n  constructor(gen: number) {\n    this.gen = gen\n  }\n\n  // no threads, so nothing more can match\n  get dead() {\n    return !this.threads.length && !this.match && !this.runs.length\n  }\n}\n\n// true if the two states hold the same threads\nconst sameState = (a: State, b: State): boolean => {\n  if (a.ids.length !== b.ids.length) return false\n  if (a.runs.length !== b.runs.length) return false\n  if (a.ids.some((id, i) => id !== b.ids[i])) return false\n  return a.runs.every(r =>\n    b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)),\n  )\n}\n\n/**\n * For each node id, the gen of the last state that has the node as\n * a thread, and of the last state that walked through it. A state is\n * built to the end before the states around it go on, and the nodes\n * of a negated sub-pattern are only in its states (other than the\n * match node, which is never marked). So one mark for each node is\n * enough to know if the state being built has it. The Sims of a\n * matcher never run at the same time, so they share one Marks.\n */\nexport type Marks = { has: Float64Array; seen: Float64Array; gen: number }\n\nconst marks = (size: number): Marks => ({\n  has: new Float64Array(size),\n  seen: new Float64Array(size),\n  gen: 0,\n})\n\nclass Sim {\n  // `.` and `..` only match literal dots, even with `dot:true`\n  dots: boolean\n  // the string starts with `.`, and `dot:true` is not set\n  dotStart: boolean\n  #marks: Marks\n\n  constructor(dots: boolean, dotStart: boolean, marks: Marks) {\n    this.dots = dots\n    this.dotStart = dotStart\n    this.#marks = marks\n  }\n\n  state() {\n    return new State(++this.#marks.gen)\n  }\n\n  // sort the ids of a state, once it has all of its threads\n  done(state: State) {\n    state.ids = state.threads.map(n => n.id).sort((a, b) => a - b)\n    if (state.match) state.ids.unshift(MATCH.id)\n    return state\n  }\n\n  // true the first time that the state walks through the node, so\n  // that loops in the graph stop\n  #visit(state: State, node: Node) {\n    const { seen } = this.#marks\n    if (seen[node.id] === state.gen) return false\n    seen[node.id] = state.gen\n    return true\n  }\n\n  #addThread(state: State, node: Node) {\n    const { has } = this.#marks\n    if (has[node.id] === state.gen) return false\n    has[node.id] = state.gen\n    state.threads.push(node)\n    return true\n  }\n\n  // wildcards only match a leading dot if `dot:true`. In a negated\n  // sub-pattern, this does not apply, because the negation itself\n  // can not match a leading dot.\n  restricted(i: number, top: boolean) {\n    return top && (this.dots || (this.dotStart && i === 0))\n  }\n\n  add(state: State, node: Node, i: number, top: boolean): void {\n    switch (node.t) {\n      case 'split':\n        if (!this.#visit(state, node)) return\n        for (const o of node.out) this.add(state, o, i, top)\n        return\n      case 'neg':\n        if (!this.#visit(state, node)) return\n        const sub = this.state()\n        this.add(sub, node.sub, i, false)\n        this.done(sub)\n        return this.addRun(\n          state,\n          { t: 'run', neg: node, state: sub },\n          i,\n          top,\n        )\n      case 'star':\n        // a * can not start a dotfile, even if it matches nothing\n        if (this.restricted(i, top)) return\n        if (this.#addThread(state, node))\n          this.add(state, node.next, i, top)\n        return\n      case 'match':\n        state.match = true\n        return\n      default:\n        this.#addThread(state, node)\n    }\n  }\n\n  addRun(state: State, run: Run, i: number, top: boolean) {\n    for (const r of state.runs) {\n      if (r.neg === run.neg && sameState(r.state, run.state)) return\n    }\n    state.runs.push(run)\n    if (!run.state.match) {\n      this.add(state, run.neg.next, i, top)\n    }\n  }\n\n  // the threads after char `c`, at index `i`\n  step(state: State, c: string, i: number, top: boolean): State {\n    const next = this.state()\n    for (const th of state.threads) {\n      switch (th.t) {\n        case 'lit':\n          if (litMatch(th, c)) {\n            this.add(next, th.next, i + 1, top)\n          }\n          break\n        case 'any':\n          if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top)\n          break\n        case 'class':\n          if (!this.restricted(i, top) && th.re.test(c)) {\n            this.add(next, th.next, i + 1, top)\n          }\n          break\n        case 'star':\n          if (!this.restricted(i, top)) this.add(next, th, i + 1, top)\n      }\n    }\n    if (!this.restricted(i, top)) {\n      for (const run of state.runs) {\n        // a sub-pattern with no threads can not match again, so the\n        // run stays the same\n        if (run.state.dead) {\n          this.addRun(next, run, i + 1, top)\n          continue\n        }\n        const sub = this.step(run.state, c, i, false)\n        this.addRun(\n          next,\n          { t: 'run', neg: run.neg, state: sub },\n          i + 1,\n          top,\n        )\n      }\n    }\n    return this.done(next)\n  }\n}\n\n// A canonical key for the threads in a state. States with the same\n// key hold the same threads, so they match the same strings.\nconst stateKey = (state: State): string => {\n  const ids = state.ids.join()\n  if (!state.runs.length) return ids\n  const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`)\n  return `${ids}|${runs.sort().join('|')}`\n}\n\n// A cached state of the simulation, and the states that each char\n// leads to.\ntype DState = {\n  state: State\n  match: boolean\n  // no threads, so nothing more can match\n  dead: boolean\n  // the next state for each ASCII char, by char code, and for the\n  // other chars\n  ascii?: (DState | undefined)[]\n  next: Map\n}\n\n// The cache can hold about this many chars of state keys and\n// transitions. When it is full, it is cleared, so that a pattern\n// can not use an unbounded amount of memory.\nconst DFA_BUDGET = 1 << 18\n\n// A cache of the states that the simulation reaches, built as the\n// matcher is used. Each char of a string is then one Map lookup,\n// once the states that it leads to are known.\n//\n// The dot rules only restrict the first char of a dotfile (strings\n// that are only `.` or `..` do not use the cache). So a dotfile\n// starts at its own state, which takes its first step with the\n// restriction, and every other state takes steps without it.\nclass Dfa {\n  #start: Node\n  #states = new Map()\n  #size = 0\n  #plain?: DState\n  #dotStart?: DState\n  #sim: Sim\n  #dotSim: Sim\n\n  constructor(start: Node, marks: Marks) {\n    this.#start = start\n    this.#sim = new Sim(false, false, marks)\n    this.#dotSim = new Sim(false, true, marks)\n  }\n\n  #make(state: State): DState {\n    return {\n      state,\n      match: state.match,\n      dead: state.dead,\n      next: new Map(),\n    }\n  }\n\n  #intern(state: State): DState {\n    const key = stateKey(state)\n    const found = this.#states.get(key)\n    if (found) return found\n    if (this.#size > DFA_BUDGET) this.#clear()\n    const d = this.#make(state)\n    this.#states.set(key, d)\n    this.#size += key.length + 1\n    return d\n  }\n\n  #clear() {\n    this.#states.clear()\n    this.#size = 0\n    this.#plain = undefined\n    this.#dotStart = undefined\n  }\n\n  start(dotStart: boolean): DState {\n    if (dotStart) {\n      if (this.#dotStart) return this.#dotStart\n      const state = this.#dotSim.state()\n      this.#dotSim.add(state, this.#start, 0, true)\n      return (this.#dotStart = this.#make(this.#dotSim.done(state)))\n    }\n    if (this.#plain) return this.#plain\n    const state = this.#sim.state()\n    this.#sim.add(state, this.#start, 0, true)\n    return (this.#plain = this.#intern(this.#sim.done(state)))\n  }\n\n  // the next state, after a miss in `d.ascii`\n  next(d: DState, c: string): DState {\n    const code = c.charCodeAt(0)\n    const found = code < 128 ? undefined : d.next.get(c)\n    if (found) return found\n    // the dotfile start is not in the cache, so it is never shared\n    const n =\n      d === this.#dotStart ?\n        this.#intern(this.#dotSim.step(d.state, c, 0, true))\n      : this.#intern(this.#sim.step(d.state, c, 1, true))\n    if (code < 128) {\n      if (!d.ascii) {\n        d.ascii = new Array(128)\n        this.#size += 128\n      }\n      d.ascii[code] = n\n    } else {\n      d.next.set(c, n)\n    }\n    this.#size++\n    return n\n  }\n}\n\n/**\n * A node in a graph with no splits or negations. Such a graph is a\n * chain of nodes that each match one char, or a `*`.\n */\nexport type LinearNode = Exclude<\n  Node,\n  SplitNode | NegNode | { t: 'match' }\n>\n\n// the nodes in order, if the graph is a single chain\nconst linear = (start: Node): LinearNode[] | undefined => {\n  const nodes: LinearNode[] = []\n  for (let n = start; n.t !== 'match'; n = n.next) {\n    if (n.t === 'split' || n.t === 'neg') return undefined\n    nodes.push(n)\n  }\n  return nodes\n}\n\n// Match a chain of nodes. Each node other than `*` matches exactly\n// one char, so on a failure it is enough to go back to the last `*`\n// and let it match one more char. This takes at most\n// nodes.length * chars.length steps.\nconst testLinear = (\n  nodes: LinearNode[],\n  chars: ArrayLike,\n  start: number,\n  end: number,\n) => {\n  let ni = 0\n  let ci = start\n  let starNi = -1\n  let starCi = 0\n  while (ci < end) {\n    const n = nodes[ni]\n    if (n?.t === 'star') {\n      starNi = ni++\n      starCi = ci\n      continue\n    }\n    const c = chars[ci]!\n    if (\n      n &&\n      (n.t === 'any' ||\n        (n.t === 'lit' && litMatch(n, c)) ||\n        (n.t === 'class' && n.re.test(c)))\n    ) {\n      ni++\n      ci++\n      continue\n    }\n    if (starNi === -1) return false\n    ni = starNi + 1\n    ci = ++starCi\n  }\n  while (nodes[ni]?.t === 'star') ni++\n  return ni === nodes.length\n}\n\n// The least and most chars that the items can match. These are only\n// bounds: a negation can match a string of any length, so it counts\n// as 0 to Infinity.\nconst lengths = (items: Item[]): [min: number, max: number] => {\n  let min = 0\n  let max = 0\n  for (const it of items) {\n    const [lo, hi] = itemLengths(it)\n    min += lo\n    max += hi\n  }\n  return [min, max]\n}\n\nconst itemLengths = (it: Item): [min: number, max: number] => {\n  if (it.t === 'star') return [0, Infinity]\n  if (it.t !== 'ext') return [1, 1]\n  if (it.type === '!') return [0, Infinity]\n  const alts = it.alts.map(lengths)\n  const min = Math.min(...alts.map(a => a[0]))\n  const max = Math.max(...alts.map(a => a[1]))\n  // a loop of alternatives that only match the empty string is empty\n  const loop = max === 0 ? 0 : Infinity\n  return (\n    it.type === '@' ? [min, max]\n    : it.type === '?' ? [0, max]\n    : it.type === '*' ? [0, loop]\n    : [min, loop]\n  )\n}\n\n// true if the chars from `start` match the literals\nconst hasAffix = (\n  lits: Lit[],\n  chars: ArrayLike,\n  start: number,\n) => {\n  for (let j = 0; j < lits.length; j++) {\n    if (!litMatch(lits[j]!, chars[start + j]!)) return false\n  }\n  return true\n}\n\n// a `/`, or half of a surrogate pair\nconst slashOrSurrogate = /[/\\ud800-\\udfff]/\nconst surrogate = /[\\ud800-\\udfff]/\n\n// a string can be indexed by code point, unless it has surrogate\n// pairs\nconst codePoints = (s: string): ArrayLike =>\n  surrogate.test(s) ? [...s] : s\n\nconst noSlash = (s: string) => {\n  if (s.includes('/')) {\n    throw new Error('can only match a single path portion, got: ' + s)\n  }\n}\n\nexport class Matcher {\n  pattern: string\n  options: MatcherOptions\n  #start: Node\n  // the number of node ids\n  #size: number\n  #marks?: Marks\n  // the Sim for strings that are only `.` or `..`\n  #dotsSim?: Sim\n  // the string to compare, if the pattern has no magic. With\n  // `nocase:true`, the RegExp that folds case is made when it is\n  // first used.\n  #literal?: string\n  #literalFold = false\n  #literalRe?: RegExp\n  // the nodes between the prefix and suffix, if the graph is a\n  // single chain\n  #linear?: LinearNode[]\n  // the linear nodes are only `*` and `?`, so the length bounds and\n  // the prefix and suffix decide the match\n  #wild = false\n  // the least and most chars that a match can have\n  #min = 0\n  #max = Infinity\n  // the literals that a match must start and end with. Each one\n  // matches exactly one char, and they are distinct items in the\n  // pattern, so a string that does not have them can not match.\n  #prefix: Lit[] = []\n  #suffix: Lit[] = []\n  // the prefix and suffix as strings, if they do not fold case\n  #prefixStr?: string\n  #suffixStr?: string\n  // there is a prefix or suffix to check\n  #affix = false\n  #dfa?: Dfa\n  #form?: Form\n\n  constructor(pattern: string, options: MatcherOptions = {}) {\n    if (pattern.includes('/')) {\n      throw new Error(\n        'can only match a single path portion, got pattern: ' + pattern,\n      )\n    }\n    this.pattern = pattern\n    this.options = options\n    const { nocase = false, noext = false, normalize: n } = options\n    this.#form = n === true ? 'NFC' : n || undefined\n    // a pattern that is only an empty extglob is a literal string,\n    // except for `!()`, which matches any non-empty string\n    const literal = /^[?*+@]\\(\\)$/.test(pattern)\n    const toks = tokenize(\n      pattern,\n      nocase,\n      noext || literal,\n      this.#form,\n      options.rangeMark,\n    )\n    let [items] = build(toks, pair(toks), 0, toks.length, true)\n    if (this.#form) items = normalize(items!, this.#form)\n    const [start, size] = compile(items!, nocase)\n    this.#start = start\n    this.#size = size\n    if (items!.every(it => it.t === 'lit')) {\n      this.#literal = items!.map(it => it.ch).join('')\n      this.#literalFold = nocase\n    } else {\n      const lit = (it: Item): Lit | undefined =>\n        it.t !== 'lit' ? undefined\n        : nocase ? { ch: it.ch, re: foldRe(it.ch) }\n        : { ch: it.ch }\n      for (const it of items!) {\n        const l = lit(it)\n        if (!l) break\n        this.#prefix.push(l)\n      }\n      for (let j = items!.length - 1; j >= 0; j--) {\n        const l = lit(items![j]!)\n        if (!l) break\n        this.#suffix.unshift(l)\n      }\n      this.#affix = !!(this.#prefix.length || this.#suffix.length)\n      if (!nocase) {\n        this.#prefixStr = this.#prefix.map(l => l.ch).join('')\n        this.#suffixStr = this.#suffix.map(l => l.ch).join('')\n      }\n      this.#linear = linear(this.#start)?.slice(\n        this.#prefix.length,\n        -this.#suffix.length || undefined,\n      )\n      this.#wild = !!this.#linear?.every(\n        n => n.t === 'star' || n.t === 'any',\n      )\n      const [min, max] = lengths(items!)\n      this.#min = min\n      this.#max = max\n    }\n  }\n\n  test(s: string): boolean {\n    // The `/` check uses the string as given, so with normalization it\n    // is a separate step. Otherwise, one scan finds both a `/` and the\n    // surrogate pairs that stop the string being indexed by code point.\n    if (this.#form) {\n      noSlash(s)\n      return this.#test(s.normalize(this.#form))\n    }\n    if (slashOrSurrogate.test(s)) {\n      noSlash(s)\n      return this.#test(s, [...s])\n    }\n    return this.#test(s, s)\n  }\n\n  /**\n   * The same as {@link Matcher#test}, but the string is not checked\n   * for `/` chars, so the result for a string that has one is not\n   * defined. Only use it for a string that is known to be one path\n   * portion, such as a part of a path that was split on `/`. It can\n   * be faster, because some patterns do not need to look at each char\n   * of the string.\n   */\n  testUnchecked(s: string): boolean {\n    return this.#test(this.#form ? s.normalize(this.#form) : s)\n  }\n\n  // Test a string that has no `/`. `chars` indexes it by code point.\n  // If it is not given, it is only found if a step needs it.\n  #test(s: string, chars?: ArrayLike): boolean {\n    if (this.#literal !== undefined) {\n      return this.#literalFold ?\n          (this.#literalRe ??= newFoldRe(this.#literal)).test(s)\n        : s === this.#literal\n    }\n    // the length check means that the prefix and suffix do not\n    // overlap. Without the chars, the length in code points is from\n    // half of the UTF-16 length (if each one is a surrogate pair) to\n    // all of it, which is often enough to know.\n    const min = this.#min\n    const max = this.#max\n    if (chars === undefined) {\n      const most = s.length\n      const least = (most + 1) >> 1\n      if (most < min || least > max) return false\n      if (least < min || most > max) chars = codePoints(s)\n    }\n    if (\n      chars !== undefined &&\n      (chars.length < min || chars.length > max)\n    ) {\n      return false\n    }\n    const prefix = this.#prefix.length\n    if (this.#affix) {\n      if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {\n        if (\n          !s.startsWith(this.#prefixStr) ||\n          !s.endsWith(this.#suffixStr)\n        ) {\n          return false\n        }\n      } else {\n        chars ??= codePoints(s)\n        const end = chars.length - this.#suffix.length\n        if (\n          !hasAffix(this.#prefix, chars, 0) ||\n          !hasAffix(this.#suffix, chars, end)\n        ) {\n          return false\n        }\n      }\n    }\n    const dotStart = !this.options.dot && s.startsWith('.')\n    if (this.#linear) {\n      // `.` and `..` only match literal dots, even with `dot:true`\n      if (s === '.' || s === '..') return false\n      // only a literal can match the leading dot. A `*` can not\n      // start a dotfile, even if it matches nothing.\n      if (dotStart && !prefix) return false\n      if (this.#wild) return true\n      chars ??= codePoints(s)\n      const end = chars.length - this.#suffix.length\n      return testLinear(this.#linear, chars, prefix, end)\n    }\n    chars ??= codePoints(s)\n    if (s === '.' || s === '..') {\n      this.#marks ??= marks(this.#size)\n      const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks))\n      const start = sim.state()\n      sim.add(start, this.#start, 0, true)\n      let state = sim.done(start)\n      for (let i = 0; i < chars.length; i++) {\n        state = sim.step(state, chars[i]!, i, true)\n      }\n      return state.match\n    }\n    this.#marks ??= marks(this.#size)\n    const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks))\n    let d = dfa.start(dotStart)\n    // read char codes from the string, so that a one-char string is\n    // only made for a cache miss\n    const str = chars === s\n    for (let i = 0; i < chars.length; i++) {\n      if (d.dead) return false\n      const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0)\n      d = d.ascii?.[code] ?? dfa.next(d, chars[i]!)\n    }\n    return d.match\n  }\n\n  /** a readable listing of the state machine */\n  toString(): string {\n    return show(this.#start)\n  }\n}\n", "const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: unknown) => void = (\n  pattern: unknown,\n): asserts pattern is string => {\n  if (typeof pattern !== 'string') {\n    throw new TypeError('invalid pattern')\n  }\n\n  if (pattern.length > MAX_PATTERN_LENGTH) {\n    throw new TypeError('pattern is too long')\n  }\n}\n", "import type { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character.  In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n */\nexport const escape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = false,\n  }: Pick = {},\n) => {\n  // don't need to escape +@! because we escape the parens\n  // that make those magic, and escaping ! as [!] isn't valid,\n  // because [!]] is a valid glob class meaning not ']'.\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/[?*()[\\]{}]/g, '[$&]')\n      : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/[?*()[\\]]/g, '[$&]')\n    : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n", "import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = true,\n  }: Pick = {},\n) => {\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/\\[([^/\\\\])\\]/g, '$1')\n      : s\n          .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n          .replace(/\\\\([^/])/g, '$1')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n    : s\n        .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n        .replace(/\\\\([^/{}])/g, '$1')\n}\n", "import { expand } from 'brace-expansion'\nimport { Matcher, type Form } from '@isaacs/nonrecursive-glob-match'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\nexport type Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  /** do not expand `{x,y}` style braces */\n  nobrace?: boolean\n  /** do not treat patterns starting with `#` as a comment */\n  nocomment?: boolean\n  /** do not treat patterns starting with `!` as a negation */\n  nonegate?: boolean\n  /** treat `**` the same as `*` */\n  noglobstar?: boolean\n  /** do not expand extglobs like `+(a|b)` */\n  noext?: boolean\n  /** return the pattern if nothing matches */\n  nonull?: boolean\n  /** treat `\\\\` as a path separator, not an escape character */\n  windowsPathsNoEscape?: boolean\n  /**\n   * inverse of {@link MinimatchOptions.windowsPathsNoEscape}\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n  /**\n   * Compare a partial path to a pattern. As long as the parts\n   * of the path that are present are not contradicted by the\n   * pattern, it will be treated as a match. This is useful in\n   * applications where you're walking through a folder structure,\n   * and don't yet have the full path, but want to ensure that you\n   * do not walk down paths that can never be a match.\n   */\n  partial?: boolean\n  /** allow matches that start with `.` even if the pattern does not */\n  dot?: boolean\n  /** ignore case */\n  nocase?: boolean\n  /** ignore case only in wildcard patterns */\n  nocaseMagicOnly?: boolean\n  /**\n   * Normalize unicode in the pattern and in each portion of the\n   * tested paths, with this form. `true` means `'NFC'`.\n   */\n  normalize?: boolean | Form\n  /** consider braces to be \"magic\" for the purpose of `hasMagic` */\n  magicalBraces?: boolean\n  /**\n   * If set, then patterns without slashes will be matched\n   * against the basename of the path if it contains slashes.\n   * For example, `a?b` would match the path `/xyz/123/acb`, but\n   * not `/xyz/acb/123`.\n   */\n  matchBase?: boolean\n  /** invert the results of negated matches */\n  flipNegate?: boolean\n  /** do not collapse multiple `/` into a single `/` */\n  preserveMultipleSlashes?: boolean\n  /**\n   * A number indicating the level of optimization that should be done\n   * to the pattern prior to parsing and using it for matches.\n   * At level 2 or higher, throws RangeError if splitting `**` and `..`\n   * would make more than `braceExpandMax` patterns, or add more than\n   * 1,000,000 path portions.\n   */\n  optimizationLevel?: number\n  /** operating system platform */\n  platform?: Platform\n  /**\n   * When a pattern starts with a UNC path or drive letter, and in\n   * `nocase:true` mode, do not convert the root portions of the\n   * pattern into a case-insensitive regular expression, and instead\n   * leave them as strings.\n   *\n   * This is the default when the platform is `win32` and\n   * `nocase:true` is set.\n   */\n  windowsNoMagicRoot?: boolean\n  /**\n   * max number of `{...}` patterns to expand. Default 100_000.\n   *\n   * At `optimizationLevel` 2 or higher, this also limits the\n   * patterns made when `**` is followed by `..`. Over this limit,\n   * construction throws a RangeError.\n   */\n  braceExpandMax?: number\n  /**\n   * Max number of non-adjacent `**` patterns to recursively walk down.\n   *\n   * The default of 200 is almost certainly high enough for most purposes,\n   * and can handle absurdly excessive patterns.\n   */\n  maxGlobstarRecursion?: number\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return cachedMinimatch(pattern, options).match(p)\n}\n\n// The Minimatch objects that minimatch() used most recently. A Map\n// keeps its keys in the order they were set, so the first key is the\n// one used least recently.\nconst cache = new Map()\nconst cacheMax = 256\nconst cachedMinimatch = (pattern: string, options: MinimatchOptions) => {\n  const key = pattern + '\\0' + JSON.stringify(options)\n  let mm = cache.get(key)\n  if (mm) {\n    cache.delete(key)\n  } else {\n    // a copy, so a later change to the options can not change it\n    mm = new Minimatch(pattern, { ...options })\n    if (cache.size >= cacheMax) {\n      cache.delete(cache.keys().next().value as string)\n    }\n  }\n  cache.set(key, mm)\n  return mm\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process ?\n    process.env?.__MINIMATCH_TESTING_PLATFORM__ || process.platform\n  : 'posix') as Platform\n\nexport type Sep = '\\\\' | '/'\n\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep =\n  defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\nexport const filter =\n  (pattern: string, options: MinimatchOptions = {}) =>\n  (p: string) =>\n    minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) =>\n      orig.defaults(ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (\n      list: string[],\n      pattern: string,\n      options: MinimatchOptions = {},\n    ) => orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  return expand(pattern, { max: options.braceExpandMax })\n}\nminimatch.braceExpand = braceExpand\n\n// A numeric range with at least this many values is matched as one\n// pattern portion, rather than expanded. For a glob walk, that is\n// one directory read, in place of a stat for each value.\nconst RANGE_MIN = 100\n// a {lo..hi} range that is not escaped, and not a ${...} variable\nconst rangeRe = /(? {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\n\n// Index of the `]` that closes the class that starts at `start`,\n// or -1 if it is not closed. Posix classes such as `[:alpha:]` are\n// not skipped, so this can find a `]` before the real end. That\n// only makes a class look less like a literal.\nconst classEnd = (pattern: string, start: number) => {\n  let i = start + 1\n  if (pattern.charAt(i) === '!' || pattern.charAt(i) === '^') i++\n  let sawStart = false\n  for (; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === ']' && sawStart) return i\n    sawStart = true\n    if (c === '\\\\') i++\n  }\n  return -1\n}\n\n// If a path portion pattern has no magic, return the string it\n// matches. Otherwise, return undefined. This can report magic for\n// a pattern that is in fact literal (eg, `[]`), but never the\n// reverse, so a string result is always safe to compare directly.\nconst literal = (pattern: string, noext: boolean): string | undefined => {\n  if (!noext && (pattern === '+()' || pattern === '@()')) return pattern\n  let lit = ''\n  for (let i = 0; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      // a trailing \\ is a literal \\\n      lit += pattern.charAt(++i) || c\n    } else if (c === '*' || c === '?') {\n      return undefined\n    } else if (c === '[') {\n      const close = classEnd(pattern, i)\n      if (close === -1) {\n        // not closed, so the [ is a literal\n        lit += c\n        continue\n      }\n      // a class of one char, such as `[*]` or `[\\b]`, is a literal\n      let body = pattern.slice(i + 1, close)\n      if (body.startsWith('\\\\')) body = body.slice(1)\n      if ([...body].length !== 1 || '!^'.includes(pattern.charAt(i + 1))) {\n        return undefined\n      }\n      lit += body\n      i = close\n    } else if (\n      !noext &&\n      '+@!'.includes(c) &&\n      pattern.charAt(i + 1) === '(' &&\n      pattern.includes(')', i + 2)\n    ) {\n      return undefined\n    } else {\n      lit += c\n    }\n  }\n  return lit\n}\n\n// True if the portion pattern has the same meaning as an alternative\n// inside `@(...)`. It must not have a `|` or `)` that is not in a\n// closed extglob (those are literal at the top level), an extglob\n// that is not closed (the `)` of the `@(...)` would close it), or a\n// trailing `\\` (it would escape the next `|`). A pattern that is\n// only an empty extglob, such as `?()`, is literal on its own, but\n// not in `@(...)`. Posix classes such as `[:alpha:]` can hide a `]`\n// from classEnd, so patterns with them are not merged.\nconst extSafe = (pattern: string) => {\n  if (/^[?*+@]\\(\\)$/.test(pattern) || pattern.includes('[:')) return false\n  let depth = 0\n  for (let i = 0; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      if (++i === pattern.length) return false\n    } else if (c === '[') {\n      const close = classEnd(pattern, i)\n      if (close !== -1) i = close\n    } else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') {\n      depth++\n      i++\n    } else if (c === ')') {\n      if (!depth--) return false\n    } else if (c === '|' && !depth) {\n      return false\n    }\n  }\n  return !depth\n}\n\n// The last path that Minimatch#match split, and its parts. A path is\n// often tested against many patterns in a row (such as a list of\n// ignore patterns), so this saves splitting it again. The parts are\n// never changed, so they can be shared.\nlet lastSplit: SplitPath | undefined\n\n/**\n * A path that Minimatch#match split, with the settings that the split\n * depends on. `resolved` is the parts after optimizationLevel 2 has\n * resolved `.` and `..` in them, which only depends on the same\n * settings, once a level 2 Minimatch has needed them.\n */\nexport type SplitPath = {\n  f: string\n  isWindows: boolean\n  preserveMultipleSlashes: boolean\n  normalize: Form | undefined\n  parts: string[]\n  resolved?: string[]\n}\n\n// The last path that Minimatch#match checked before splitting it. If\n// the same path is checked again, it is being tested against many\n// patterns, so it is split and the parts are kept for the others.\nlet lastChecked: string | undefined\n\nexport type ParseReturnFiltered = string | Matcher | typeof GLOBSTAR\n\n/**\n * The rows that Minimatch#match can match without splitting the path:\n * `**` and one more portion (`tail`), a portion with `**` on each side\n * of it (`mid`), a portion and then `**` (`head`), or one portion that\n * matches the basename of the path, with matchBase (`base`).\n */\nexport type RowShape = 'tail' | 'mid' | 'head' | 'base'\n\n// true if a pattern portion that is not ** matches a path portion.\n// An empty path portion only matches an empty pattern portion. A path\n// portion never has a `/`, so the Matcher does not need to check it.\nconst portionMatch = (p: string | Matcher, f: string) =>\n  typeof p === 'string' ? f === p : f !== '' && p.testUnchecked(f)\n\n// Where the last portion of a row matches in a path: the start of the\n// last portion of the path, or of the one before a trailing `/`. -1 if\n// it matches neither.\nconst endIndex = (\n  p: string | Matcher,\n  last: string,\n  lastStart: number,\n  prev: string | undefined,\n  prevStart: number,\n) =>\n  portionMatch(p, last) ? lastStart\n  : prev !== undefined && portionMatch(p, prev) ? prevStart\n  : -1\n\nconst isDots = (p: string) => p === '.' || p === '..'\n\n// a Windows drive letter portion, like `c:`\nconst isDrive = (p: ParseReturn | undefined) =>\n  typeof p === 'string' && /^[a-z]:$/i.test(p)\n\n// true for the `UNC` portion of a long UNC root, //?/UNC/host/share\nconst isLongUNC = (p: ParseReturn | undefined) =>\n  typeof p === 'string' && /^unc$/i.test(p)\n\n// The index of the host in a row or split path that starts with a\n// Windows UNC root: 2 for `//host/share`, and 4 for\n// `//?/UNC/host/share`. Otherwise -1. `//?/c:` is not one.\nconst uncHost = (p: ParseReturn[]) => {\n  if (p[0] !== '' || p[1] !== '') return -1\n  const h =\n    p[2] !== '?' ? 2\n    : isLongUNC(p[3]) ? 4\n    : -1\n  const host = p[h]\n  const share = p[h + 1]\n  return (\n      h !== -1 &&\n        host !== undefined &&\n        host !== '' &&\n        host !== GLOBSTAR &&\n        share !== undefined &&\n        share !== '' &&\n        share !== GLOBSTAR\n    ) ?\n      h\n    : -1\n}\n\n// true if ** can walk the path portion: not `.` or `..`, and not a\n// dotfile unless `dot` is set\nconst walkable = (p: string, dot: boolean) =>\n  !isDots(p) && (dot || !p.startsWith('.'))\n\n// True if a portion of the path from `start` to `end` can not be\n// walked by **: one that starts with `.`, or with `dot`, one that is\n// `.` or `..`. `start` is the start of a portion, and `end` is the end\n// of the path, or just after a separator.\nconst dotPortion = (\n  f: string,\n  start: number,\n  end: number,\n  dot: boolean,\n  sep: PathSeps,\n) => {\n  for (let k = start; k < end;) {\n    if (f.charCodeAt(k) === 46) {\n      if (!dot) return true\n      const n = f.charCodeAt(k + 1) === 46 ? k + 2 : k + 1\n      if (n >= end || isSep(f.charCodeAt(n), sep)) return true\n    }\n    // the start of the next portion, after any run of separators\n    const s = nextSep(f, k, sep)\n    if (s === -1) return false\n    k = s + 1\n    while (k < end && isSep(f.charCodeAt(k), sep)) k++\n  }\n  return false\n}\n\n/**\n * The separators that a path has: only `/`, only `\\` (a Windows path\n * with no `/`), or both. Scanning for the ones it has is faster.\n */\nexport type PathSeps = '/' | '\\\\' | 'both'\n\nconst isSep = (c: number, sep: PathSeps) =>\n  sep === '/' ? c === 47\n  : sep === '\\\\' ? c === 92\n  : c === 47 || c === 92\n\n// the index of the first separator at or after `from`, or -1\nconst nextSep = (f: string, from: number, sep: PathSeps) => {\n  if (sep !== 'both') return f.indexOf(sep, from)\n  const s = f.indexOf('/', from)\n  const b = f.indexOf('\\\\', from)\n  return (\n    s === -1 ? b\n    : b === -1 ? s\n    : Math.min(s, b)\n  )\n}\n\n// the index of the last separator at or before `from`, or -1\nconst lastSep = (f: string, from: number, sep: PathSeps) =>\n  sep !== 'both' ?\n    f.lastIndexOf(sep, from)\n  : Math.max(f.lastIndexOf('/', from), f.lastIndexOf('\\\\', from))\n\n/**\n * A pattern row split on its first and last `**`, from a start\n * index. Each body segment has the number of path portions that it\n * and the ones after it need, to find the last index where it can\n * start in a path.\n */\nexport type GlobstarParts = {\n  head: ParseReturn[]\n  body: ParseReturn[]\n  tail: ParseReturn[]\n  segments: [segment: ParseReturn[], need: number][]\n}\nexport type ParseReturn = ParseReturnFiltered | false\n\n// What parse() returns in place of a Matcher while make() builds and\n// merges the rows. Most of the Matchers in rows that are merged would\n// never be used, so they are only made for the rows that are left.\nconst PENDING = {} as Matcher\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n  maxGlobstarRecursion: number\n  // the path can be checked against the last portion, and the string\n  // portions, of each row before it is split. See #canMatch.\n  #endCheck: boolean\n  #literalCheck: boolean\n  // level 2 resolves `.` and `..` portions in the path\n  #level2: boolean\n  // the unicode normalization form, if any\n  #form: Form | undefined\n  // the string portions of each row in the set\n  #literals: string[][] = []\n  // the rows that #canMatch can match without splitting the path\n  #shapes: (RowShape | undefined)[] = []\n  // the rows whose last portion can be checked against the path's\n  #endRows: boolean[] = []\n  // brace expansion can make the same portion in many rows, so they\n  // share one Matcher, and the states that it caches\n  #matchers = new Map()\n  // parse() returns PENDING in place of a Matcher\n  #pending = false\n  // the char that marks numeric ranges in globSet, if any\n  #rangeMark?: string\n  // the GlobstarParts of each pattern row, by start index and partial\n  #globstarParts = new WeakMap()\n\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    // avoid the annoying deprecation flag lol\n    const awe = ('allowWindow' + 'sEscape') as keyof MinimatchOptions\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options[awe] === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined ?\n        options.windowsNoMagicRoot\n      : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n    this.#endCheck = !this.preserveMultipleSlashes\n    this.#level2 = (options.optimizationLevel ?? 1) >= 2\n    const n = options.normalize\n    this.#form = n === true ? 'NFC' : n || undefined\n\n    // make the set of Matchers etc.\n    this.make()\n\n    // On Windows, the portions of a row up to its drive letter or UNC\n    // share are skipped or compared without case, if the path has one\n    // too. So the checks only use the portions after it.\n    const drives = this.set.map(row => this.#rootIndex(row))\n    this.#endRows = this.set.map(\n      (row, r) => this.#endCheck && row.length - 1 > drives[r]!,\n    )\n    // with the end check, the last portion is already checked\n    this.#literals = this.set.map((row, r) => {\n      const end = this.#endRows[r] ? row.length - 1 : row.length\n      const lits = row\n        .slice(drives[r]! + 1, end)\n        .filter((p): p is string => typeof p === 'string' && !!p)\n      return [...new Set(lits)]\n    })\n    this.#literalCheck = this.#literals.some(l => l.length)\n    this.#shapes = this.set.map((row, r) => {\n      const [p0, p1, p2] = row\n      if (this.#endRows[r] && row.length === 2) {\n        if (p0 === GLOBSTAR && p1 !== GLOBSTAR) return 'tail'\n      }\n      // the basename of a path that is split on / is its last portion,\n      // or the one before a trailing /, the same as the end check\n      if (\n        this.#endRows[r] &&\n        options.matchBase &&\n        row.length === 1 &&\n        p0 !== GLOBSTAR &&\n        p0 !== ''\n      ) {\n        return 'base'\n      }\n      // the portion must not be a root, or '', which can be a\n      // different portion on Windows (where //x paths get an extra '')\n      if (!this.#endCheck || drives[r] !== -1) return undefined\n      if (\n        row.length === 3 &&\n        p0 === GLOBSTAR &&\n        p2 === GLOBSTAR &&\n        p1 !== GLOBSTAR &&\n        p1 !== '' &&\n        // the portion between is only matched below this limit\n        this.maxGlobstarRecursion > 0\n      ) {\n        return 'mid'\n      }\n      if (\n        row.length === 2 &&\n        p1 === GLOBSTAR &&\n        p0 !== GLOBSTAR &&\n        p0 !== ''\n      ) {\n        return 'head'\n      }\n      return undefined\n    })\n  }\n\n  // a string portion of a pattern, normalized if the option is set\n  #norm(p: string) {\n    return this.#form ? p.normalize(this.#form) : p\n  }\n\n  // On Windows, the index of the last root portion of a row, as\n  // #matchRow finds it: 0 for `c:/...`, 3 for `//?/c:/...` and\n  // `//host/share/...`, and 5 for `//?/UNC/host/share/...`. Otherwise\n  // -1.\n  #rootIndex(row: ParseReturn[]) {\n    if (!this.isWindows) return -1\n    if (isDrive(row[0])) return 0\n    const uncDrive =\n      row[0] === '' && row[1] === '' && row[2] === '?' && isDrive(row[3])\n    if (uncDrive) return 3\n    const h = uncHost(row)\n    return h === -1 ? -1 : h + 1\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.#expandBraces())]\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be Matchers, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.#slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n\n    // glob --> Matchers\n    this.#pending = true\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path. The root of a long UNC\n        // path, //?/UNC/host/share, is 6 portions.\n        const n = s[2] === '?' && isLongUNC(s[3]) ? 6 : 4\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          s.slice(3, n).every(p => !globMagic.test(p))\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [\n            ...s.slice(0, n).map(p => this.#norm(p)),\n            ...s.slice(n).map(ss => this.parse(ss)),\n          ]\n        } else if (isDrive) {\n          return [\n            this.#norm(s[0]!),\n            ...s.slice(1).map(ss => this.parse(ss)),\n          ]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1,\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          (isDrive(p[3]) || isLongUNC(this.globParts[i][3]))\n        ) {\n          if (isLongUNC(this.globParts[i][3])) p[3] = 'UNC'\n          p[2] = '?'\n        }\n      }\n    }\n\n    // with noext, `@(...)` would be literal\n    if (!options.noext) this.mergeRows()\n\n    this.#pending = false\n    this.set.forEach((row, i) => {\n      for (let k = 0; k < row.length; k++) {\n        if (row[k] === PENDING) {\n          row[k] = this.parse(this.globParts[i]![k]!) as Matcher\n        }\n      }\n    })\n  }\n\n  // Merge rows that only differ in one portion, where each of them\n  // is a Matcher, into one row that matches any of them with\n  // `@(a|b|...)`. Then a path is only walked once for all of them,\n  // for example with `**/*.{js,ts}`.\n  mergeRows() {\n    let merged = true\n    while (merged) {\n      merged = false\n      const len = Math.max(0, ...this.set.map(r => r.length))\n      for (let k = 0; k < len; k++) {\n        // the rows that are the same other than at portion k\n        const groups = new Map()\n        this.set.forEach((row, i) => {\n          if (\n            !(row[k] instanceof Matcher || row[k] === PENDING) ||\n            !extSafe(this.globParts[i]![k]!)\n          ) {\n            return\n          }\n          const parts = [...this.globParts[i]!]\n          parts[k] = ''\n          const key = `${row.length}/${parts.join('/')}`\n          const g = groups.get(key)\n          if (g) g.push(i)\n          else groups.set(key, [i])\n        })\n        const drop = new Set()\n        for (const g of groups.values()) {\n          if (g.length < 2) continue\n          const [first, ...rest] = g as [number, ...number[]]\n          const alts = g.map(i => this.globParts[i]![k]!)\n          const glob = `@(${alts.join('|')})`\n          this.globParts[first]![k] = glob\n          this.set[first]![k] = this.parse(glob) as Matcher\n          for (const i of rest) drop.add(i)\n        }\n        if (drop.size) {\n          merged = true\n          this.set = this.set.filter((_, i) => !drop.has(i))\n          this.globParts = this.globParts.filter((_, i) => !drop.has(i))\n        }\n      }\n    }\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn ** into *\n    if (this.options.noglobstar) {\n      for (const partset of globParts) {\n        for (let j = 0; j < partset.length; j++) {\n          if (partset[j] === '**') {\n            partset[j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      // .. can not remove the root of a Windows path\n      const root = this.#rootIndex(parts) + 1\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (\n            set.length > root &&\n            prev &&\n            prev !== '..' &&\n            prev !== '.' &&\n            prev !== '**'\n          ) {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  // Check the path against each row before it is split. 'no' if no\n  // row can match, so it does not need to be split. 'yes' if a row of\n  // `**` and one more portion matches. 'maybe' if it must be split to\n  // know. None of this applies with partial, where the path can end\n  // before the row does.\n  //\n  // On Windows, `\\` is a separator in the path too, and the portions of\n  // a row up to its drive letter or UNC share are not checked (see\n  // #rootIndex).\n  //\n  // Each string portion of a row must be a portion of the path, so the\n  // path must contain it. Level 2 can only take portions out of the\n  // path, so this is still true then.\n  //\n  // The last portion of a row must match the last portion of the path,\n  // or the one before a trailing `/` (as a/* and a/**/* match a/b/).\n  // This does not apply to rows that end in **, rows that end in a\n  // root, or preserveMultipleSlashes (which can leave more\n  // than one '' at the end). At level 2, it does not apply if that\n  // portion is `.` or `..`, which can be\n  // resolved away. Level 2 only takes other portions out of the\n  // middle of the path.\n  //\n  // A row of `**/x` then matches if the ** can walk the portions\n  // before the one that x matches, the same as #matchGlobstar. At\n  // level 2, this is only known if none of them are `.` or `..`, so\n  // that the path does not change when it is resolved.\n  #canMatch(f: string): 'no' | 'yes' | 'maybe' {\n    const sep: PathSeps =\n      !this.isWindows || !f.includes('\\\\') ? '/'\n      : f.includes('/') ? 'both'\n      : '\\\\'\n    // the portions that f.split(/\\/+/) would end with, and where they\n    // start in f, found when a row needs them. `ends` is 0 until they\n    // are found, then 1, or -1 if they can not be used.\n    let ends = this.#endCheck ? 0 : -1\n    let last = ''\n    let lastStart = 0\n    let prev: string | undefined\n    let prevStart = 0\n    const dot = !!this.options.dot\n    // A string compare is cheaper than includes(), and a Matcher test\n    // costs more, so the cheaper check goes first.\n    ROWS: for (let r = 0; r < this.set.length; r++) {\n      const row = this.set[r]!\n      const p = row[row.length - 1]\n      let end = ends !== -1 && this.#endRows[r]! && p !== GLOBSTAR\n      if (end && ends === 0) {\n        const i = lastSep(f, f.length, sep)\n        lastStart = i + 1\n        last = f.slice(lastStart)\n        if (last === '' && i >= 0) {\n          let j = i\n          while (j > 0 && isSep(f.charCodeAt(j - 1), sep)) j--\n          prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep) + 1\n          prev = f.slice(prevStart, j)\n        }\n        const resolves =\n          this.#level2 &&\n          (isDots(last) ||\n            (last === '' && prev !== undefined && isDots(prev)))\n        ends = resolves ? -1 : 1\n        end = !resolves\n      }\n      let tailStart = -1\n      if (end && typeof p === 'string') {\n        tailStart = endIndex(p, last, lastStart, prev, prevStart)\n        if (tailStart === -1) continue\n      }\n      if (this.#literalCheck) {\n        for (const l of this.#literals[r]!) {\n          if (!f.includes(l)) continue ROWS\n        }\n      }\n      if (end && typeof p === 'object') {\n        tailStart = endIndex(p, last, lastStart, prev, prevStart)\n        if (tailStart === -1) continue\n      }\n      const shape = this.#shapes[r]\n      if (shape === 'base' && end) return 'yes'\n      if (shape === 'tail' && end) {\n        if (this.#level2 && dotPortion(f, 0, tailStart, true, sep)) {\n          return 'maybe'\n        }\n        if (!dotPortion(f, 0, tailStart, dot, sep)) return 'yes'\n        continue\n      }\n      if (shape === 'mid' || shape === 'head') {\n        const m = this.#walk(f, row, shape === 'head', dot, sep)\n        if (m !== 'no') return m\n        continue\n      }\n      return 'maybe'\n    }\n    return 'no'\n  }\n\n  // Match a row of a known shape against the split path, the same as\n  // #matchGlobstar and #matchGlobStarBodySections do. None of these\n  // rows have a drive letter, so they start at the first portion.\n  #matchShape(\n    file: string[],\n    row: ParseReturnFiltered[],\n    shape: 'tail' | 'mid' | 'head',\n  ): boolean {\n    const dot = !!this.options.dot\n    const n = file.length\n    if (shape === 'head') {\n      // x, then at least one portion that ** can walk\n      if (n < 2 || !portionMatch(row[0] as string | Matcher, file[0]!)) {\n        return false\n      }\n      for (let i = 1; i < n; i++)\n        if (!walkable(file[i]!, dot)) return false\n      return true\n    }\n    const x = row[1] as string | Matcher\n    if (shape === 'tail') {\n      // x is the last portion, or the one before a trailing ''\n      let t = n - 1\n      if (!portionMatch(x, file[t]!)) {\n        if (file[t] !== '' || n === 1 || !portionMatch(x, file[--t]!)) {\n          return false\n        }\n      }\n      for (let i = 0; i < t; i++)\n        if (!walkable(file[i]!, dot)) return false\n      return true\n    }\n    // mid: the first x that ** can walk to, with a portion after it,\n    // and ** can walk all of those\n    for (let k = 0; k < n; k++) {\n      if (portionMatch(x, file[k]!) && k + 1 < n) {\n        let i = k + 1\n        while (i < n && walkable(file[i]!, dot)) i++\n        if (i === n) return true\n      }\n      if (!walkable(file[k]!, dot)) return false\n    }\n    return false\n  }\n\n  // Match a row of `**/x/**` or `x/**` against the path, the same as\n  // #matchGlobstar and #matchGlobStarBodySections do once it is split.\n  // x must match a portion (the first one, for `x/**`), the ** before\n  // it must be able to walk the portions before that one, and there\n  // must be a portion after it, which the ** after it can walk. At\n  // level 2, this is only known if no portion is `.` or `..`.\n  #walk(\n    f: string,\n    row: ParseReturnFiltered[],\n    head: boolean,\n    dot: boolean,\n    sep: PathSeps,\n  ): 'yes' | 'no' | 'maybe' {\n    if (this.#level2 && dotPortion(f, 0, f.length, true, sep))\n      return 'maybe'\n    const x = row[head ? 0 : 1] as string | Matcher\n    // the last portion has none after it, so it can not be x\n    let s = 0\n    for (let e = nextSep(f, s, sep); e !== -1; e = nextSep(f, s, sep)) {\n      // the start of the next portion\n      let next = e + 1\n      while (next < f.length && isSep(f.charCodeAt(next), sep)) next++\n      const hit =\n        typeof x === 'string' ?\n          e - s === x.length && f.startsWith(x, s)\n        : e > s && x.testUnchecked(f.slice(s, e))\n      if (hit && !dotPortion(f, next, f.length, dot, sep)) return 'yes'\n      if (head || dotPortion(f, s, next, dot, sep)) return 'no'\n      s = next\n    }\n    return 'no'\n  }\n\n  // the last split, if it was the same path with the same split\n  // settings\n  #cachedSplit(f: string) {\n    const last = lastSplit\n    return (\n        last?.f === f &&\n          last.isWindows === this.isWindows &&\n          last.preserveMultipleSlashes === this.preserveMultipleSlashes &&\n          last.normalize === this.#form\n      ) ?\n        last\n      : undefined\n  }\n\n  // split a path for match(), and keep the parts for the next call\n  #split(f: string) {\n    const { isWindows, preserveMultipleSlashes } = this\n    // windows: need to use /, not \\\n    let parts = this.#slashSplit(isWindows ? f.split('\\\\').join('/') : f)\n    // normalize each portion, so that a char that normalizes to `/`\n    // does not make a new portion\n    const normalize = this.#form\n    if (normalize) parts = parts.map(p => p.normalize(normalize))\n    lastSplit = {\n      f,\n      isWindows,\n      preserveMultipleSlashes,\n      normalize,\n      parts,\n    }\n    return lastSplit\n  }\n\n  // resolve `.` and `..` portions of a path, for level 2\n  #levelTwoFileOptimize(file: string[]) {\n    // work on a copy, so that the cached parts do not change\n    const parts = [...file]\n    let didSomething: boolean = false\n\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      // .. can not remove the root of a Windows path\n      const root = this.#rootIndex(parts) + 1\n      let dd: number = root\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd = Math.max(dd - 2, root)\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    // each **/.. split doubles the patterns, and adds a copy of the\n    // whole pattern. Throw if either gets too large. A partial split\n    // would match some paths and not others, depending on which rows\n    // the pass reached first.\n    const { braceExpandMax = 100_000 } = this.options\n    let splitCells = 0\n    const maxSplitCells = 1_000_000\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          // Check before changing parts or allocating the new row.\n          const addedCells = parts.length - 1\n          if (\n            globParts.length >= braceExpandMax ||\n            splitCells + addedCells > maxSplitCells\n          ) {\n            throw new RangeError(\n              `optimizationLevel 2: too many patterns from '**/..'`,\n            )\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          splitCells += addedCells\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        // .. can not remove the root of a Windows path\n        const root = this.#rootIndex(parts) + 1\n        let dd: number = root\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd = Math.max(dd - 2, root)\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/,
/} -> 
/\n  // {
/*/,
/

/} ->

/*/\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    const keys = new Set()\n    const rows = globParts.filter(parts => {\n      const key = parts.join('/')\n      if (keys.has(key)) return false\n      keys.add(key)\n      return true\n    })\n\n    // A row is covered by another row that has `*` at some positions,\n    // and is the same at all others. Collect each distinct set of `*`\n    // positions, then look up each row with `*` put at those positions.\n    const stars = new Map()\n    for (const parts of rows) {\n      const s: number[] = []\n      for (let i = 0; i < parts.length; i++) {\n        if (parts[i] === '*') s.push(i)\n      }\n      if (s.length) stars.set(s.join(','), s)\n    }\n    // Each row is checked against each set of `*` positions, so skip\n    // this if there are too many. The patterns match the same paths\n    // either way.\n    if (!stars.size || rows.length * stars.size > 100_000) return rows\n\n    const { dot } = this.options\n    return rows.filter(parts => {\n      for (const s of stars.values()) {\n        if (s[s.length - 1]! >= parts.length) continue\n        const c = [...parts]\n        let ok = true\n        let changed = false\n        for (const i of s) {\n          const p = parts[i]!\n          if (p === '*') continue\n          if (!p || p === '**' || (!dot && p.startsWith('.'))) {\n            ok = false\n            break\n          }\n          c[i] = '*'\n          changed = true\n        }\n        if (ok && changed && keys.has(c.join('/'))) return false\n      }\n      return true\n    })\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // Match the parts of a path against one row of the set. `resolved`\n  // is the parts after level 2 resolves `.` and `..` in them, or the\n  // same parts below level 2. Set partial to true to test if, for\n  // example, \"/a/b\" matches the start of \"/*/b/*/d\". Partial means, if\n  // you run out of file before you run out of pattern, then that's\n  // fine, as long as all the parts match.\n  #matchRow(\n    file: string[],\n    resolved: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n  ) {\n    let fileStartIndex = 0\n    let patternStartIndex = 0\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa, and\n    // //?/UNC/host/share/... can match //host/share/... and vice versa.\n    // Drive letters in absolute drive or unc paths, and the host and\n    // share of UNC paths, are always compared case-insensitively.\n    const fh = this.isWindows ? uncHost(resolved) : -1\n    const ph = fh === -1 ? -1 : uncHost(pattern)\n    if (ph !== -1) {\n      const host = pattern[ph]\n      const share = pattern[ph + 1]\n      if (typeof host !== 'string' || typeof share !== 'string') {\n        // a host or share with magic is matched as usual\n        fileStartIndex = fh\n        patternStartIndex = ph\n      } else if (\n        resolved[fh]!.toLowerCase() === host.toLowerCase() &&\n        resolved[fh + 1]!.toLowerCase() === share.toLowerCase()\n      ) {\n        fileStartIndex = fh + 2\n        patternStartIndex = ph + 2\n      }\n    } else if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi =\n        fileUNC ? 3\n        : fileDrive ? 0\n        : undefined\n      const pdi =\n        patternUNC ? 3\n        : patternDrive ? 0\n        : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        // the drives match, so start matching after them\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          patternStartIndex = pdi + 1\n          fileStartIndex = fdi + 1\n        }\n      }\n    }\n\n    // the drive letters are found in the parts before level 2 resolves\n    // them, and the match uses the resolved parts\n    file = resolved\n\n    if (pattern.includes(GLOBSTAR)) {\n      return this.#matchGlobstar(\n        file,\n        pattern,\n        partial,\n        fileStartIndex,\n        patternStartIndex,\n      )\n    }\n\n    return this.#matchOne(\n      file,\n      pattern,\n      partial,\n      fileStartIndex,\n      patternStartIndex,\n    )\n  }\n\n  #matchGlobstar(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n  ) {\n    const { head, body, tail, segments } = this.#getGlobstarParts(\n      pattern,\n      partial,\n      patternIndex,\n    )\n\n    // check the head, from the current file/pattern index.\n    if (head.length) {\n      const headEnd = fileIndex + head.length\n      if (!this.#matchOne(file, head, partial, fileIndex, 0, headEnd)) {\n        return false\n      }\n      fileIndex += head.length\n      patternIndex += head.length\n    }\n    // now we know the head matches!\n\n    // if the last portion is not empty, it MUST match the end\n    // check the tail\n    let fileTailMatch: number = 0\n    if (tail.length) {\n      // if head + tail > file, then we cannot possibly match\n      if (tail.length + fileIndex > file.length) return false\n\n      // try to match the tail\n      let tailStart = file.length - tail.length\n      if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n        fileTailMatch = tail.length\n      } else {\n        // affordance for stuff like a/**/* matching a/b/\n        // if the last file portion is '', and there's more to the pattern\n        // then try without the '' bit.\n        if (\n          file[file.length - 1] !== '' ||\n          fileIndex + tail.length === file.length\n        ) {\n          return false\n        }\n        tailStart--\n        if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n          return false\n        }\n        fileTailMatch = tail.length + 1\n      }\n    }\n\n    // now we know the tail matches!\n\n    // the middle is zero or more portions wrapped in **, possibly\n    // containing more ** sections.\n    // so a/**/b/**/c/**/d has become **/b/**/c/**\n    // if it's empty, it means a/**/b, just verify we have no bad dots\n    // if there's no tail, so it ends on /**, then we must have *something*\n    // after the head, or it's not a matc\n    if (!body.length) {\n      let sawSome = !!fileTailMatch\n      for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n        const f = String(file[i])\n        sawSome = true\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      // in partial mode, we just need to get past all file parts\n      return partial || sawSome\n    }\n\n    // now we know that there's one or more body sections, which can\n    // be matched anywhere from the 0 index (because the head was pruned)\n    // through to the length-fileTailMatch index.\n    return !!this.#matchGlobStarBodySections(\n      file,\n      segments,\n      file.length - fileTailMatch,\n      fileIndex,\n      0,\n      partial,\n      0,\n      !!fileTailMatch,\n      new Set(),\n    )\n  }\n\n  // Split the pattern into head, tail, and middle of ** delimited\n  // parts. The tail has to be at the end, and the others just have to\n  // be found in order from the head. These only depend on the pattern\n  // row, so they are kept for the next path.\n  #getGlobstarParts(\n    pattern: ParseReturn[],\n    partial: boolean,\n    patternIndex: number,\n  ): GlobstarParts {\n    let byStart = this.#globstarParts.get(pattern)\n    if (!byStart) {\n      byStart = []\n      this.#globstarParts.set(pattern, byStart)\n    }\n    const key = patternIndex * 2 + (partial ? 1 : 0)\n    const found = byStart[key]\n    if (found) return found\n\n    const firstgs = pattern.indexOf(GLOBSTAR, patternIndex)\n    const lastgs = pattern.lastIndexOf(GLOBSTAR)\n    const head = pattern.slice(patternIndex, firstgs)\n    const body = pattern.slice(firstgs + 1, partial ? undefined : lastgs)\n    const tail = partial ? [] : pattern.slice(lastgs + 1)\n\n    // split the body up into sections, and note the number of\n    // portions that must come after the start of each one\n    const segments: [ParseReturn[], number][] = [[[], 0]]\n    let current = segments[0]!\n    let nonGsParts = 0\n    const nonGsPartsSums: number[] = [0]\n    for (const b of body) {\n      if (b === GLOBSTAR) {\n        nonGsPartsSums.push(nonGsParts)\n        current = [[], 0]\n        segments.push(current)\n      } else {\n        current[0].push(b)\n        nonGsParts++\n      }\n    }\n    // the portions in this section and the ones after it\n    segments.forEach((b, i) => {\n      b[1] = nonGsParts - (nonGsPartsSums[i] as number)\n    })\n\n    const parts = { head, body, tail, segments }\n    byStart[key] = parts\n    return parts\n  }\n\n  // return false for \"nope, not matching\"\n  // return null for \"not matching, cannot keep trying\"\n  #matchGlobStarBodySections(\n    file: string[],\n    // pattern section, and the portions that it and the rest need\n    bodySegments: [ParseReturn[], number][],\n    // the end of the file portions that the body can match\n    fileLength: number,\n    fileIndex: number,\n    bodyIndex: number,\n    partial: boolean,\n    globStarDepth: number,\n    sawTail: boolean,\n    // the places that a walk has already tried, as\n    // bodyIndex * (file.length + 1) + fileIndex. A walk from a place\n    // does the same no matter how it got there, and it only comes back\n    // if it found no match, so a walk that gets to one stops.\n    tried: Set,\n  ): boolean | null {\n    // take the first body segment, and walk from fileIndex to its \"after\"\n    // value at the end\n    // If it doesn't match at that position, we increment, until we hit\n    // that final possible position, and give up.\n    // If it does match, then advance and try to rest.\n    // If any of them fail we keep walking forward.\n    // this is still a bit recursively painful, but it's more constrained\n    // than previous implementations, because we never test something that\n    // can't possibly be a valid matching condition.\n    const bs = bodySegments[bodyIndex]\n    if (!bs) {\n      // with partial, the body is the rest of the pattern, so it\n      // matches if no portions are left, or only the '' of a trailing\n      // / (as a/* matches a/b/). A ** at the end walks them as its own\n      // empty section.\n      if (partial) {\n        return (\n          fileIndex >= fileLength ||\n          (fileIndex === fileLength - 1 && file[fileIndex] === '')\n        )\n      }\n      // just make sure that there's no bad dots before the tail\n      for (let i = fileIndex; i < fileLength; i++) {\n        sawTail = true\n        const f = file[i]\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      return sawTail\n    }\n\n    // have a non-globstar body section to test, up to the last index\n    // where it can start\n    const [body, need] = bs\n    // with partial, the path can end before the body does\n    const after = partial ? fileLength : fileLength - need\n    while (fileIndex <= after) {\n      const key = bodyIndex * (file.length + 1) + fileIndex\n      if (tried.has(key)) return false\n      tried.add(key)\n      const m = this.#matchOne(\n        file,\n        body,\n        partial,\n        fileIndex,\n        0,\n        fileIndex + body.length,\n      )\n      // if limit exceeded, no match. intentional false negative,\n      // acceptable break in correctness for security.\n      if (m && globStarDepth < this.maxGlobstarRecursion) {\n        // match! see if the rest match. if so, we're done!\n        const sub = this.#matchGlobStarBodySections(\n          file,\n          bodySegments,\n          fileLength,\n          fileIndex + body.length,\n          bodyIndex + 1,\n          partial,\n          globStarDepth + 1,\n          sawTail,\n          tried,\n        )\n        if (sub !== false) {\n          return sub\n        }\n      }\n      // the ** does not walk past the last place the body can start\n      if (fileIndex === after) break\n      const f = file[fileIndex]!\n      if (\n        f === '.' ||\n        f === '..' ||\n        (!this.options.dot && f.startsWith('.'))\n      ) {\n        return false\n      }\n\n      fileIndex++\n    }\n    // walked off. no point continuing\n    return partial || null\n  }\n\n  #matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n    // only match the file portions before this index\n    fileEnd: number = file.length,\n  ) {\n    let fi: number\n    let pi: number\n    let pl: number\n    let fl: number\n    for (\n      fi = fileIndex,\n        pi = patternIndex,\n        fl = Math.min(fileEnd, file.length),\n        pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      let p = pattern[pi]\n      let f = file[fi]\n\n      // should be impossible.\n      /* c8 ignore start */\n      if (p === false || p === GLOBSTAR) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into Matchers.\n      if (!portionMatch(p, f)) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though * can match \"\", except in\n    // partial mode, where it might simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  // Expand braces, except numeric ranges such as {0..999} with at\n  // least RANGE_MIN values. Each of those stays in its pattern as\n  // `0..999`, for the Matcher to test. If a range might\n  // be inside a [...] class, expand all of them instead.\n  #expandBraces(): string[] {\n    const { pattern } = this\n    if (this.options.nobrace) return this.braceExpand()\n    let code = 0xe000\n    while (pattern.includes(String.fromCharCode(code))) {\n      if (++code > 0xf8ff) return this.braceExpand()\n    }\n    const mark = String.fromCharCode(code)\n    let found = false\n    const marked = pattern.replace(\n      rangeRe,\n      (m, lo: string, hi: string) => {\n        const a = Number(lo)\n        const b = Number(hi)\n        if (\n          !Number.isSafeInteger(a) ||\n          !Number.isSafeInteger(b) ||\n          Math.abs(a - b) + 1 < RANGE_MIN\n        ) {\n          return m\n        }\n        found = true\n        return `${mark}${lo}..${hi}${mark}`\n      },\n    )\n    if (!found) return this.braceExpand()\n    const set = braceExpand(marked, this.options)\n    for (const p of set) {\n      for (const portion of p.split('/')) {\n        const c = portion.indexOf('[')\n        if (c !== -1 && c < portion.lastIndexOf(mark)) {\n          return this.braceExpand()\n        }\n      }\n    }\n    this.#rangeMark = mark\n    return set\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    const {\n      nocase,\n      nocaseMagicOnly,\n      noext = false,\n      dot,\n      normalize,\n    } = options\n    const rangeMark = this.#rangeMark\n    const lit =\n      rangeMark && pattern.includes(rangeMark) ?\n        undefined\n      : literal(pattern, noext)\n    // in nocase mode, a literal with cased chars still needs a\n    // Matcher, unless nocaseMagicOnly is set.\n    if (\n      lit !== undefined &&\n      !(\n        nocase &&\n        !nocaseMagicOnly &&\n        pattern.toUpperCase() !== pattern.toLowerCase()\n      )\n    ) {\n      return this.#norm(lit)\n    }\n\n    if (this.#pending) return PENDING\n    let m = this.#matchers.get(pattern)\n    if (!m) {\n      m = new Matcher(pattern, {\n        nocase,\n        noext,\n        dot,\n        normalize,\n        ...(rangeMark && { rangeMark }),\n      })\n      this.#matchers.set(pattern, m)\n    }\n    return m\n  }\n\n  #slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // treat the test path as a set of pathparts. If it was not just\n    // split or checked, check that it can match before splitting it.\n    let split = this.#cachedSplit(f)\n    if (!split) {\n      // the checks look at the path as given, so not if it is\n      // normalized\n      if (\n        !partial &&\n        !this.#form &&\n        (this.#endCheck || this.#literalCheck) &&\n        lastChecked !== f\n      ) {\n        lastChecked = f\n        const can = this.#canMatch(f)\n        if (can === 'no') return options.flipNegate ? false : this.negate\n        if (can === 'yes') return options.flipNegate ? true : !this.negate\n      }\n      split = this.#split(f)\n    }\n    const ff = split.parts\n    // the parts after level 2 resolves them, kept for the next pattern\n    // that tests the same path\n    const resolved =\n      this.#level2 ?\n        (split.resolved ??= this.#levelTwoFileOptimize(ff))\n      : ff\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let r = 0; r < set.length; r++) {\n      const pattern = set[r]!\n      const shape = partial ? undefined : this.#shapes[r]\n      // level 2 does not change a path of one portion\n      const hit =\n        shape === 'base' ?\n          portionMatch(pattern[0] as string | Matcher, filename)\n        : shape ? this.#matchShape(resolved, pattern, shape)\n        : options.matchBase && pattern.length === 1 ?\n          this.#matchRow([filename], [filename], pattern, partial)\n        : this.#matchRow(ff, resolved, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\nexport type { Form }\n/* c8 ignore stop */\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n", "import type { Form, MinimatchOptions } from 'minimatch'\nimport { Minimatch } from 'minimatch'\nimport type { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport type { FSOption, Path } from 'path-scurry'\nimport {\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport type { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be either a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignored` and `childrenIgnored`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  readonly ignore?: string | string[] | IgnoreLike | ReadonlyArray\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Normalize unicode in the pattern, and in the file names that it is\n   * matched against, with this form: `'NFC'`, `'NFD'`, `'NFKC'`, or\n   * `'NFKD'`. `true` means `'NFC'`. This is passed to minimatch, so it\n   * applies to the portions of the pattern with magic, and to the\n   * `ignore` patterns.\n   *\n   * The portions of the pattern without magic are looked up with\n   * path-scurry, which already compares the names of the entries\n   * that it knows in their `'NFKD'` form.\n   */\n  normalize?: boolean | Form\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n\n  /**\n   * max number of `{...}` patterns to expand. Default `1_000`.\n   *\n   * Note: this is much less than minimatch's default of `100_000`,\n   * because Glob has higher memory requirements due to walking\n   * the file system tree.\n   */\n  braceExpandMax?: number\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike | ReadonlyArray\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[] | ReadonlyArray\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    let p: string[] = typeof pattern === 'string' ? [pattern] : pattern\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      p = p.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      p = p.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = p\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      braceExpandMax: 10_000,\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      // default nocase based on platform\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return await new GlobWalker(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).walk()\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return new GlobWalker(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).walkSync()\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n", "// simple node version that imports from node builtin\n// this is built to both ESM and CommonJS on the 'node' import path\nimport { tracingChannel, channel } from 'node:diagnostics_channel'\nimport type { TracingChannel, Channel } from 'node:diagnostics_channel'\nexport type { TracingChannel, Channel }\nexport const metrics: Channel = channel('lru-cache:metrics')\nexport const tracing: TracingChannel = tracingChannel('lru-cache')\n", "/**\n * this provides the default Perf object source, either the\n * `performance` global, or the `Date` constructor.\n *\n * it can be passed in via configuration to override it\n * for a single LRU object.\n */\nexport type Perf = { now: () => number }\nexport const defaultPerf: Perf =\n  (\n    typeof performance === 'object' &&\n    performance &&\n    typeof performance.now === 'function'\n  ) ?\n    /* c8 ignore start - this gets covered, but c8 gets confused */\n    performance\n  : /* c8 ignore stop */ Date\n", "/**\n * @module LRUCache\n */\n\nimport { metrics, tracing } from './diagnostics-channel.js'\nimport { defaultPerf } from './perf.js'\nimport type { Perf } from './perf.js'\nexport type { Perf } from './perf.js'\n\nconst hasSubscribers = () =>\n  metrics.hasSubscribers || tracing.hasSubscribers\n\nconst warned = new Set()\n\n// either a function or a class\n// oxlint-disable-next-line no-explicit-any\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n  typeof process === 'object' && !!process ?\n    process\n  : {}) as { [k: string]: unknown }\n/* c8 ignore stop */\n\nconst emitWarning = (\n  msg: string,\n  type: string,\n  code: string,\n  fn: ForC,\n) => {\n  if (typeof PROCESS.emitWarning === 'function') {\n    PROCESS.emitWarning(msg, type, code, fn)\n  } else {\n    //oxlint-disable-next-line no-console\n    console.error(`[${code}] ${type}: ${msg}`)\n  }\n}\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: unknown): n is PosInt =>\n  !!n && n === Math.floor(n as number) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values.  Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\n/* c8 ignore start */\nconst getUintArray = (max: number) =>\n  !isPosInt(max) ? null\n  : max <= Math.pow(2, 8) ? Uint8Array\n  : max <= Math.pow(2, 16) ? Uint16Array\n  : max <= Math.pow(2, 32) ? Uint32Array\n  : max <= Number.MAX_SAFE_INTEGER ? ZeroArray\n  : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array {\n  constructor(size: number) {\n    super(size)\n    this.fill(0)\n  }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n  /* c8 ignore start - not sure why this is showing up uncovered?? */\n  heap: NumberArray\n  /* c8 ignore stop */\n  length: number\n  // private constructor\n  static #constructing: boolean = false\n  static create(max: number): StackLike {\n    const HeapCls = getUintArray(max)\n    if (!HeapCls) return []\n    Stack.#constructing = true\n    const s = new Stack(max, HeapCls)\n    Stack.#constructing = false\n    return s\n  }\n  constructor(max: number, HeapCls: { new (n: number): NumberArray }) {\n    /* c8 ignore start */\n    if (!Stack.#constructing) {\n      throw new TypeError('instantiate Stack using Stack.create(n)')\n    }\n    /* c8 ignore stop */\n    this.heap = new HeapCls(max)\n    this.length = 0\n  }\n  push(n: Index) {\n    this.heap[this.length++] = n\n  }\n  pop(): Index {\n    return this.heap[--this.length] as Index\n  }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch = Promise & {\n  __returned: BackgroundFetch | undefined\n  __abortController: AbortController\n  __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask = [\n  value: V,\n  key: K,\n  reason: LRUCache.DisposeReason,\n]\n\nexport namespace LRUCache {\n  /**\n   * An integer greater than 0, reflecting the calculated size of items\n   */\n  export type Size = number\n\n  /**\n   * Integer greater than 0, representing some number of milliseconds, or the\n   * time at which a TTL started counting from.\n   */\n  export type Milliseconds = number\n\n  /**\n   * An integer greater than 0, reflecting a number of items\n   */\n  export type Count = number\n\n  /**\n   * The reason why an item was removed from the cache, passed\n   * to the {@link Disposer} methods.\n   *\n   * - `evict`: The item was evicted because it is the least recently used,\n   *   and the cache is full.\n   * - `set`: A new value was set, overwriting the old value being disposed.\n   * - `delete`: The item was explicitly deleted, either by calling\n   *   {@link LRUCache#delete}, {@link LRUCache#clear}, or\n   *   {@link LRUCache#set} with an undefined value.\n   * - `expire`: The item was removed due to exceeding its TTL.\n   * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n   *   `undefined` or was aborted, causing the item to be deleted.\n   */\n  export type DisposeReason =\n    | 'evict'\n    | 'set'\n    | 'delete'\n    | 'expire'\n    | 'fetch'\n  /**\n   * A method called upon item removal, passed as the\n   * {@link OptionsBase.dispose} and/or\n   * {@link OptionsBase.disposeAfter} options.\n   */\n  export type Disposer = (\n    value: V,\n    key: K,\n    reason: DisposeReason,\n  ) => void\n\n  /**\n   * The reason why an item was added to the cache, passed\n   * to the {@link Inserter} methods.\n   *\n   * - `add`: the item was not found in the cache, and was added\n   * - `update`: the item was in the cache, with the same value provided\n   * - `replace`: the item was in the cache, and replaced\n   */\n  export type InsertReason = 'add' | 'update' | 'replace'\n\n  /**\n   * A method called upon item insertion, passed as the\n   * {@link OptionsBase.insert}\n   */\n  export type Inserter = (\n    value: V,\n    key: K,\n    reason: InsertReason,\n  ) => void\n\n  /**\n   * A function that returns the effective calculated size\n   * of an entry in the cache.\n   */\n  export type SizeCalculator = (value: V, key: K) => Size\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.fetchMethod} function.\n   */\n  export interface FetcherOptions {\n    signal: AbortSignal\n    options: FetcherFetchOptions\n    /**\n     * Object provided in the {@link FetchOptions.context} option to\n     * {@link LRUCache#fetch}\n     */\n    context: FC\n  }\n\n  /**\n   * Occasionally, it may be useful to track the internal behavior of the\n   * cache, particularly for logging, debugging, or for behavior within the\n   * `fetchMethod`. To do this, you can pass a `status` object to the\n   * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n   * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n   *\n   * The `status` option should be a plain JavaScript object. The following\n   * fields will be set on it appropriately, depending on the situation.\n   *\n   * These objects are also the context objects passed to listeners on the\n   * `lru-cache:metrics` diagnostic channel, and the `lru-cache` tracing\n   * channels, in platforms that support them.\n   */\n  export interface Status {\n    /**\n     * The operation being performed\n     */\n    op?: 'get' | 'set' | 'memo' | 'fetch' | 'delete' | 'has' | 'peek'\n    /**\n     * The status of a set() operation.\n     *\n     * - add: the item was not found in the cache, and was added\n     * - update: the item was in the cache, with the same value provided\n     * - replace: the item was in the cache, and replaced\n     * - miss: the item was not added to the cache for some reason\n     */\n    set?: 'add' | 'update' | 'replace' | 'miss' | 'deleted'\n\n    /**\n     * The status of a delete() operation.\n     */\n    delete?: LRUCache.DisposeReason\n\n    /**\n     * The result of a peek() operation\n     *\n     * - hit: the item was found and returned\n     * - stale: the item is in the cache, but past its ttl and not returned\n     * - miss: item not in the cache\n     */\n    peek?: 'hit' | 'miss' | 'stale'\n\n    /**\n     * The status of a memo() operation.\n     *\n     * - 'hit': the item was found in the cache and returned\n     * - 'miss': the `memoMethod` function was called\n     */\n    memo?: 'hit' | 'miss'\n\n    /**\n     * The `context` option provided to a memo or fetch operation\n     *\n     * In practice, of course, this will be the same type as the `FC`\n     * fetch context param used to instantiate the LRUCache, but the\n     * convolutions of threading that through would get quite complicated,\n     * and preclude forcing/forbidding the passing of a `context` param\n     * where it is/isn't expected, which is more valuable for error\n     * prevention.\n     */\n    context?: unknown\n\n    /**\n     * the ttl stored for the item, or undefined if ttls are not used.\n     */\n    ttl?: Milliseconds\n\n    /**\n     * the start time for the item, or undefined if ttls are not used.\n     */\n    start?: Milliseconds\n\n    /**\n     * The timestamp used for TTL calculation\n     */\n    now?: Milliseconds\n\n    /**\n     * the remaining ttl for the item, or undefined if ttls are not used.\n     */\n    remainingTTL?: Milliseconds\n\n    /**\n     * The calculated size for the item, if sizes are used.\n     */\n    entrySize?: Size\n\n    /**\n     * The total calculated size of the cache, if sizes are used.\n     */\n    totalCalculatedSize?: Size\n\n    /**\n     * A flag indicating that the item was not stored, due to exceeding the\n     * {@link OptionsBase.maxEntrySize}\n     */\n    maxEntrySizeExceeded?: true\n\n    /**\n     * The key that was set or retrieved\n     */\n    key?: K\n\n    /**\n     * The value that was set\n     */\n    value?: V\n\n    /**\n     * The old value, specified in the case of `set:'replace'`\n     */\n    oldValue?: V\n\n    /**\n     * The results of a {@link LRUCache#has} operation\n     *\n     * - hit: the item was found in the cache\n     * - stale: the item was found in the cache, but is stale\n     * - miss: the item was not found in the cache\n     */\n    has?: 'hit' | 'stale' | 'miss'\n\n    /**\n     * The status of a {@link LRUCache#fetch} operation.\n     * Note that this can change as the underlying fetch() moves through\n     * various states.\n     *\n     * - inflight: there is another fetch() for this key which is in process\n     * - get: there is no {@link OptionsBase.fetchMethod}, so\n     *   {@link LRUCache#get} was called.\n     * - miss: the item is not in cache, and will be fetched.\n     * - hit: the item is in the cache, and was resolved immediately.\n     * - stale: the item is in the cache, but stale.\n     * - refresh: the item is in the cache, and not stale, but\n     *   {@link FetchOptions.forceRefresh} was specified.\n     */\n    fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n    /**\n     * `forceRefresh` option was used for either a fetch or memo operation\n     */\n    forceRefresh?: boolean\n\n    /**\n     * The {@link OptionsBase.fetchMethod} was called\n     */\n    fetchDispatched?: true\n\n    /**\n     * The cached value was updated after a successful call to\n     * {@link OptionsBase.fetchMethod}\n     */\n    fetchUpdated?: true\n\n    /**\n     * The reason for a fetch() rejection.  Either the error raised by the\n     * {@link OptionsBase.fetchMethod}, or the reason for an\n     * AbortSignal.\n     */\n    fetchError?: Error\n\n    /**\n     * The fetch received an abort signal\n     */\n    fetchAborted?: true\n\n    /**\n     * The abort signal received was ignored, and the fetch was allowed to\n     * continue in the background.\n     */\n    fetchAbortIgnored?: true\n\n    /**\n     * The fetchMethod promise resolved successfully\n     */\n    fetchResolved?: true\n\n    /**\n     * The fetchMethod promise was rejected\n     */\n    fetchRejected?: true\n\n    /**\n     * The status of a {@link LRUCache#get} operation.\n     *\n     * - fetching: The item is currently being fetched.  If a previous value\n     *   is present and allowed, that will be returned.\n     * - stale: The item is in the cache, and is stale. If it was returned,\n     *   then the `returnedStale` flag will be set.\n     * - stale-fetching: The value is being fetched in the background, but is\n     *   currently stale. If the stale value was returned, then the\n     *   `returnedStale` flag will be set.\n     * - hit: the item is in the cache\n     * - miss: the item is not in the cache\n     */\n    get?: 'stale' | 'hit' | 'miss' | 'fetching' | 'stale-fetching'\n\n    /**\n     * A fetch or get operation returned a stale value.\n     */\n    returnedStale?: true\n\n    /**\n     * A tracingChannel trace was started for this operation\n     */\n    trace?: boolean\n\n    /**\n     * A reference to the cache instance associated with this operation\n     */\n    cache?: LRUCache\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#fetch}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link OptionsBase.noDeleteOnFetchRejection},\n   * {@link OptionsBase.allowStaleOnFetchRejection},\n   * {@link FetchOptions.forceRefresh}, and\n   * {@link FetcherOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the fetchMethod is called.\n   */\n  export interface FetcherFetchOptions extends Pick<\n    OptionsBase,\n    | 'allowStale'\n    | 'updateAgeOnGet'\n    | 'noDeleteOnStaleGet'\n    | 'sizeCalculation'\n    | 'ttl'\n    | 'noDisposeOnSet'\n    | 'noUpdateTTL'\n    | 'noDeleteOnFetchRejection'\n    | 'allowStaleOnFetchRejection'\n    | 'ignoreFetchAbort'\n    | 'allowStaleOnFetchAbort'\n  > {\n    status?: Status\n    size?: Size\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#fetch} method.\n   */\n  export interface FetchOptions extends FetcherFetchOptions<\n    K,\n    V,\n    FC\n  > {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.fetchMethod} as\n     * the {@link FetcherOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    signal?: AbortSignal\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface FetchOptionsWithContext extends FetchOptions<\n    K,\n    V,\n    FC\n  > {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface FetchOptionsNoContext<\n    K,\n    V,\n    FC extends undefined | void = undefined,\n  > extends FetchOptions {\n    context?: FC\n  }\n\n  export interface MemoOptions extends Pick<\n    OptionsBase,\n    | 'allowStale'\n    | 'updateAgeOnGet'\n    | 'noDeleteOnStaleGet'\n    | 'sizeCalculation'\n    | 'ttl'\n    | 'noDisposeOnSet'\n    | 'noUpdateTTL'\n    | 'noDeleteOnFetchRejection'\n    | 'allowStaleOnFetchRejection'\n    | 'ignoreFetchAbort'\n    | 'allowStaleOnFetchAbort'\n  > {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.memoMethod} as\n     * the {@link MemoizerOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface MemoOptionsWithContext extends MemoOptions<\n    K,\n    V,\n    FC\n  > {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface MemoOptionsNoContext<\n    K,\n    V,\n    FC extends undefined | void = undefined,\n  > extends MemoOptions {\n    context?: FC\n  }\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.memoMethod} function.\n   */\n  export interface MemoizerOptions {\n    options: MemoizerMemoOptions\n    /**\n     * Object provided in the {@link MemoOptions.context} option to\n     * {@link LRUCache#memo}\n     */\n    context: FC\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#memo}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link MemoOptions.forceRefresh}, and\n   * {@link MemoOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.memoMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the memoMethod is called.\n   */\n  export interface MemoizerMemoOptions extends Pick<\n    OptionsBase,\n    | 'allowStale'\n    | 'updateAgeOnGet'\n    | 'noDeleteOnStaleGet'\n    | 'sizeCalculation'\n    | 'ttl'\n    | 'noDisposeOnSet'\n    | 'noUpdateTTL'\n  > {\n    status?: Status\n    size?: Size\n    start?: Milliseconds\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#has} method.\n   */\n  export interface HasOptions extends Pick<\n    OptionsBase,\n    'updateAgeOnHas'\n  > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#get} method.\n   */\n  export interface GetOptions extends Pick<\n    OptionsBase,\n    'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n  > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#peek} method.\n   */\n  export interface PeekOptions extends Pick<\n    OptionsBase,\n    'allowStale'\n  > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#set} method.\n   */\n  export interface SetOptions extends Pick<\n    OptionsBase,\n    'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n  > {\n    /**\n     * If size tracking is enabled, then setting an explicit size\n     * in the {@link LRUCache#set} call will prevent calling the\n     * {@link OptionsBase.sizeCalculation} function.\n     */\n    size?: Size\n    /**\n     * If TTL tracking is enabled, then setting an explicit start\n     * time in the {@link LRUCache#set} call will override the\n     * default time from `performance.now()` or `Date.now()`.\n     *\n     * Note that it must be a valid value for whichever time-tracking\n     * method is in use.\n     */\n    start?: Milliseconds\n    status?: Status\n  }\n\n  /**\n   * The type signature for the {@link OptionsBase.fetchMethod} option.\n   */\n  export type Fetcher = (\n    key: K,\n    staleValue: V | undefined,\n    options: FetcherOptions,\n  ) => Promise | V | undefined | void\n\n  /**\n   * the type signature for the {@link OptionsBase.memoMethod} option.\n   */\n  export type Memoizer = (\n    key: K,\n    staleValue: V | undefined,\n    options: MemoizerOptions,\n  ) => V\n\n  /**\n   * Options which may be passed to the {@link LRUCache} constructor.\n   *\n   * Most of these may be overridden in the various options that use\n   * them.\n   *\n   * Despite all being technically optional, the constructor requires that\n   * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n   * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n   *\n   * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n   * (and in fact required by the type definitions here) that the cache\n   * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n   * unbounded storage.\n   *\n   * All options are also available on the {@link LRUCache} instance, making\n   * it safe to pass an LRUCache instance as the options argumemnt to\n   * make another empty cache of the same type.\n   *\n   * Some options are marked as read-only, because changing them after\n   * instantiation is not safe. Changing any of the other options will of\n   * course only have an effect on subsequent method calls.\n   */\n  export interface OptionsBase {\n    /**\n     * The maximum number of items to store in the cache before evicting\n     * old entries. This is read-only on the {@link LRUCache} instance,\n     * and may not be overridden.\n     *\n     * If set, then storage space will be pre-allocated at construction\n     * time, and the cache will perform significantly faster.\n     *\n     * Note that significantly fewer items may be stored, if\n     * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n     * set.\n     *\n     * **It is strongly recommended to set a `max` to prevent unbounded growth\n     * of the cache.**\n     */\n    max?: Count\n\n    /**\n     * Max time in milliseconds for items to live in cache before they are\n     * considered stale.  Note that stale items are NOT preemptively removed by\n     * default, and MAY live in the cache, contributing to its LRU max, long\n     * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n     * set.\n     *\n     * If set to `0` (the default value), then that means \"do not track\n     * TTL\", not \"expire immediately\".\n     *\n     * Also, as this cache is optimized for LRU/MRU operations, some of\n     * the staleness/TTL checks will reduce performance, as they will incur\n     * overhead by deleting items.\n     *\n     * This is not primarily a TTL cache, and does not make strong TTL\n     * guarantees. There is no pre-emptive pruning of expired items, but you\n     * _may_ set a TTL on the cache, and it will treat expired items as missing\n     * when they are fetched, and delete them.\n     *\n     * Optional, but must be a non-negative integer in ms if specified.\n     *\n     * This may be overridden by passing an options object to `cache.set()`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if ttl tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n     * and `ttlAutopurge` is not set, then a warning will be emitted\n     * cautioning about the potential for unbounded memory consumption.\n     * (The TypeScript definitions will also discourage this.)\n     */\n    ttl?: Milliseconds\n\n    /**\n     * Minimum amount of time in ms in which to check for staleness.\n     * Defaults to 1, which means that the current time is checked\n     * at most once per millisecond.\n     *\n     * Set to 0 to check the current time every time staleness is tested.\n     * (This reduces performance, and is theoretically unnecessary.)\n     *\n     * Setting this to a higher value will improve performance somewhat\n     * while using ttl tracking, albeit at the expense of keeping stale\n     * items around a bit longer than their TTLs would indicate.\n     *\n     * @default 1\n     */\n    ttlResolution?: Milliseconds\n\n    /**\n     * Preemptively remove stale items from the cache.\n     *\n     * Note that this may *significantly* degrade performance, especially if\n     * the cache is storing a large number of items. It is almost always best\n     * to just leave the stale items in the cache, and let them fall out as new\n     * items are added.\n     *\n     * Note that this means that {@link OptionsBase.allowStale} is a bit\n     * pointless, as stale items will be deleted almost as soon as they\n     * expire.\n     *\n     * Use with caution!\n     */\n    ttlAutopurge?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever it is retrieved from cache with\n     * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n     * of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     */\n    updateAgeOnGet?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever its presence in the cache is\n     * checked with {@link LRUCache#has}, causing it to not expire. (It can\n     * still fall out of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     */\n    updateAgeOnHas?: boolean\n\n    /**\n     * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n     * stale data, if available.\n     *\n     * By default, if you set `ttl`, stale items will only be deleted from the\n     * cache when you `get(key)`. That is, it's not preemptively pruning items,\n     * unless {@link OptionsBase.ttlAutopurge} is set.\n     *\n     * If you set `allowStale:true`, it'll return the stale value *as well as*\n     * deleting it. If you don't set this, then it'll return `undefined` when\n     * you try to get a stale entry.\n     *\n     * Note that when a stale entry is fetched, _even if it is returned due to\n     * `allowStale` being set_, it is removed from the cache immediately. You\n     * can suppress this behavior by setting\n     * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n     * the options provided to {@link LRUCache#get}.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     * The `cache.has()` method will always return `false` for stale items.\n     *\n     * Only relevant if a ttl is set.\n     */\n    allowStale?: boolean\n\n    /**\n     * Function that is called on items when they are dropped from the\n     * cache, as `dispose(value, key, reason)`.\n     *\n     * This can be handy if you want to close file descriptors or do\n     * other cleanup tasks when items are no longer stored in the cache.\n     *\n     * **NOTE**: It is called _before_ the item has been fully removed\n     * from the cache, so if you want to put it right back in, you need\n     * to wait until the next tick. If you try to add it back in during\n     * the `dispose()` function call, it will break things in subtle and\n     * weird ways.\n     *\n     * Unlike several other options, this may _not_ be overridden by\n     * passing an option to `set()`, for performance reasons.\n     *\n     * The `reason` will be one of the following strings, corresponding\n     * to the reason for the item's deletion:\n     *\n     * - `evict` Item was evicted to make space for a new addition\n     * - `set` Item was overwritten by a new value\n     * - `expire` Item expired its TTL\n     * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n     *   fetchMethod returning `undefined.\n     * - `delete` Item was removed by explicit `cache.delete(key)`,\n     *   `cache.clear()`, or `cache.set(key, undefined)`.\n     */\n    dispose?: Disposer\n\n    /**\n     * Function that is called when new items are inserted into the cache,\n     * as `onInsert(value, key, reason)`.\n     *\n     * This can be useful if you need to perform actions when an item is\n     * added, such as logging or tracking insertions.\n     *\n     * Unlike some other options, this may _not_ be overridden by passing\n     * an option to `set()`, for performance and consistency reasons.\n     */\n    onInsert?: Inserter\n\n    /**\n     * The same as {@link OptionsBase.dispose}, but called *after* the entry\n     * is completely removed and the cache is once again in a clean state.\n     *\n     * It is safe to add an item right back into the cache at this point.\n     * However, note that it is *very* easy to inadvertently create infinite\n     * recursion this way.\n     */\n    disposeAfter?: Disposer\n\n    /**\n     * Set to true to suppress calling the\n     * {@link OptionsBase.dispose} function if the entry key is\n     * still accessible within the cache.\n     *\n     * This may be overridden by passing an options object to\n     * {@link LRUCache#set}.\n     *\n     * Only relevant if `dispose` or `disposeAfter` are set.\n     */\n    noDisposeOnSet?: boolean\n\n    /**\n     * Boolean flag to tell the cache to not update the TTL when setting a new\n     * value for an existing key (ie, when updating a value rather than\n     * inserting a new value).  Note that the TTL value is _always_ set (if\n     * provided) when adding a new entry into the cache.\n     *\n     * Has no effect if a {@link OptionsBase.ttl} is not set.\n     *\n     * May be passed as an option to {@link LRUCache#set}.\n     */\n    noUpdateTTL?: boolean\n\n    /**\n     * Set to a positive integer to track the sizes of items added to the\n     * cache, and automatically evict items in order to stay below this size.\n     * Note that this may result in fewer than `max` items being stored.\n     *\n     * Attempting to add an item to the cache whose calculated size is greater\n     * that this amount will be a no-op. The item will not be cached, and no\n     * other items will be evicted.\n     *\n     * Optional, must be a positive integer if provided.\n     *\n     * Sets `maxEntrySize` to the same value, unless a different value is\n     * provided for `maxEntrySize`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if size tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * Note also that size tracking can negatively impact performance,\n     * though for most cases, only minimally.\n     */\n    maxSize?: Size\n\n    /**\n     * The effective size for background fetch promises.\n     *\n     * This has no effect unless `maxSize` and `sizeCalculation` are used,\n     * and a {@link LRUCache.OptionsBase.fetchMethod} is provided to\n     * support {@link LRUCache#fetch}.\n     *\n     * If a stale value is present in the cache, then the effective size of\n     * the background fetch is the size of the stale item it will eventually\n     * replace. If not, then this value is used as its effective size.\n     *\n     * @default 1\n     */\n    backgroundFetchSize?: number\n\n    /**\n     * The maximum allowed size for any single item in the cache.\n     *\n     * If a larger item is passed to {@link LRUCache#set} or returned by a\n     * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n     * it will not be stored in the cache.\n     *\n     * Attempting to add an item whose calculated size is greater than\n     * this amount will not cache the item or evict any old items, but\n     * WILL delete an existing value if one is already present.\n     *\n     * Optional, must be a positive integer if provided. Defaults to\n     * the value of `maxSize` if provided.\n     */\n    maxEntrySize?: Size\n\n    /**\n     * A function that returns a number indicating the item's size.\n     *\n     * Requires {@link OptionsBase.maxSize} to be set.\n     *\n     * If not provided, and {@link OptionsBase.maxSize} or\n     * {@link OptionsBase.maxEntrySize} are set, then all\n     * {@link LRUCache#set} calls **must** provide an explicit\n     * {@link SetOptions.size} or sizeCalculation param.\n     */\n    sizeCalculation?: SizeCalculator\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#fetch}\n     *\n     * ```ts\n     * fetchMethod(key, staleValue, { signal, options, context })\n     * ```\n     *\n     * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n     * to `Promise.resolve(cache.get(key))`.\n     *\n     * If at any time, `signal.aborted` is set to `true`, or if the\n     * `signal.onabort` method is called, or if it emits an `'abort'` event\n     * which you can listen to with `addEventListener`, then that means that\n     * the fetch should be abandoned. This may be passed along to async\n     * functions aware of AbortController/AbortSignal behavior.\n     *\n     * The `fetchMethod` should **only** return `undefined` or a Promise\n     * resolving to `undefined` if the AbortController signaled an `abort`\n     * event. In all other cases, it should return or resolve to a value\n     * suitable for adding to the cache.\n     *\n     * The `options` object is a union of the options that may be provided to\n     * `set()` and `get()`. If they are modified, then that will result in\n     * modifying the settings to `cache.set()` when the value is resolved, and\n     * in the case of\n     * {@link OptionsBase.noDeleteOnFetchRejection} and\n     * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n     * `fetchMethod` failures.\n     *\n     * For example, a DNS cache may update the TTL based on the value returned\n     * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n     */\n    fetchMethod?: Fetcher\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#memo}\n     */\n    memoMethod?: Memoizer\n\n    /**\n     * Set to true to suppress the deletion of stale data when a\n     * {@link OptionsBase.fetchMethod} returns a rejected promise.\n     */\n    noDeleteOnFetchRejection?: boolean\n\n    /**\n     * Do not delete stale items when they are retrieved with\n     * {@link LRUCache#get}.\n     *\n     * Note that the `get` return value will still be `undefined`\n     * unless {@link OptionsBase.allowStale} is true.\n     *\n     * When using time-expiring entries with `ttl`, by default stale\n     * items will be removed from the cache when the key is accessed\n     * with `cache.get()`.\n     *\n     * Setting this option will cause stale items to remain in the cache, until\n     * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n     * `noDeleteOnStaleGet` set to `false`.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     *\n     * Only relevant if a ttl is used.\n     */\n    noDeleteOnStaleGet?: boolean\n\n    /**\n     * Set to true to allow returning stale data when a\n     * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n     * promise.\n     *\n     * This differs from using {@link OptionsBase.allowStale} in that stale\n     * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n     * fails, not any other times.\n     *\n     * If a `fetchMethod` fails, and there is no stale value available, the\n     * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n     * suppressed.\n     *\n     * Implies `noDeleteOnFetchRejection`.\n     *\n     * This may be set in calls to `fetch()`, or defaulted on the constructor,\n     * or overridden by modifying the options object in the `fetchMethod`.\n     */\n    allowStaleOnFetchRejection?: boolean\n\n    /**\n     * Set to true to return a stale value from the cache when the\n     * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n     * an `'abort'` event, whether user-triggered, or due to internal cache\n     * behavior.\n     *\n     * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n     * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n     * any value it returns will be ignored and not cached.\n     *\n     * Caveat: since fetches are aborted when a new value is explicitly\n     * set in the cache, this can lead to fetch returning a stale value,\n     * since that was the fallback value _at the moment the `fetch()` was\n     * initiated_, even though the new updated value is now present in\n     * the cache.\n     *\n     * For example:\n     *\n     * ```ts\n     * const cache = new LRUCache({\n     *   ttl: 100,\n     *   fetchMethod: async (url, oldValue, { signal }) =>  {\n     *     const res = await fetch(url, { signal })\n     *     return await res.json()\n     *   }\n     * })\n     * cache.set('https://example.com/', { some: 'data' })\n     * // 100ms go by...\n     * const result = cache.fetch('https://example.com/')\n     * cache.set('https://example.com/', { other: 'thing' })\n     * console.log(await result) // { some: 'data' }\n     * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n     * ```\n     */\n    allowStaleOnFetchAbort?: boolean\n\n    /**\n     * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n     * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n     * resulting resolution value, as long as it is not `undefined`.\n     *\n     * When used on its own, this means aborted {@link LRUCache#fetch} calls\n     * are not immediately resolved or rejected when they are aborted, and\n     * instead take the full time to await.\n     *\n     * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n     * {@link LRUCache#fetch} calls will resolve immediately to their stale\n     * cached value or `undefined`, and will continue to process and eventually\n     * update the cache when they resolve, as long as the resulting value is\n     * not `undefined`, thus supporting a \"return stale on timeout while\n     * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n     *\n     * For example:\n     *\n     * ```ts\n     * const c = new LRUCache({\n     *   ttl: 100,\n     *   ignoreFetchAbort: true,\n     *   allowStaleOnFetchAbort: true,\n     *   fetchMethod: async (key, oldValue, { signal }) => {\n     *     // note: do NOT pass the signal to fetch()!\n     *     // let's say this fetch can take a long time.\n     *     const res = await fetch(`https://slow-backend-server/${key}`)\n     *     return await res.json()\n     *   },\n     * })\n     *\n     * // this will return the stale value after 100ms, while still\n     * // updating in the background for next time.\n     * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n     * ```\n     *\n     * **Note**: regardless of this setting, an `abort` event _is still\n     * emitted on the `AbortSignal` object_, so may result in invalid results\n     * when passed to other underlying APIs that use AbortSignals.\n     *\n     * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n     * call to {@link LRUCache#fetch}.\n     */\n    ignoreFetchAbort?: boolean\n\n    /**\n     * In some cases, you may want to swap out the performance/Date object\n     * used for TTL tracking. This should almost certainly NOT be done in\n     * production environments!\n     *\n     * This value defaults to `global.performance` if it has a `now()` method,\n     * or the `global.Date` object otherwise.\n     */\n    perf?: Perf\n  }\n\n  export interface OptionsMaxLimit extends OptionsBase<\n    K,\n    V,\n    FC\n  > {\n    max: Count\n  }\n  export interface OptionsTTLLimit extends OptionsBase<\n    K,\n    V,\n    FC\n  > {\n    ttl: Milliseconds\n    ttlAutopurge: boolean\n  }\n  export interface OptionsSizeLimit extends OptionsBase<\n    K,\n    V,\n    FC\n  > {\n    maxSize: Size\n  }\n\n  /**\n   * The valid safe options for the {@link LRUCache} constructor\n   */\n  export type Options =\n    | OptionsMaxLimit\n    | OptionsSizeLimit\n    | OptionsTTLLimit\n\n  /**\n   * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n   * and returned by {@link LRUCache#info}.\n   */\n  export interface Entry {\n    value: V\n    ttl?: Milliseconds\n    size?: Size\n    start?: Milliseconds\n  }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache {\n  // options that cannot be changed without disaster\n  readonly #max: LRUCache.Count\n  readonly #maxSize: LRUCache.Size\n  readonly #dispose?: LRUCache.Disposer\n  readonly #onInsert?: LRUCache.Inserter\n  readonly #disposeAfter?: LRUCache.Disposer\n  readonly #fetchMethod?: LRUCache.Fetcher\n  readonly #memoMethod?: LRUCache.Memoizer\n  readonly #perf: Perf\n\n  /**\n   * {@link LRUCache.OptionsBase.perf}\n   */\n  get perf() {\n    return this.#perf\n  }\n\n  /**\n   * {@link LRUCache.OptionsBase.ttl}\n   */\n  ttl: LRUCache.Milliseconds\n\n  /**\n   * {@link LRUCache.OptionsBase.ttlResolution}\n   */\n  ttlResolution: LRUCache.Milliseconds\n  /**\n   * {@link LRUCache.OptionsBase.ttlAutopurge}\n   */\n  ttlAutopurge: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnGet}\n   */\n  updateAgeOnGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnHas}\n   */\n  updateAgeOnHas: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStale}\n   */\n  allowStale: boolean\n\n  /**\n   * {@link LRUCache.OptionsBase.noDisposeOnSet}\n   */\n  noDisposeOnSet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noUpdateTTL}\n   */\n  noUpdateTTL: boolean\n  /**\n   * {@link LRUCache.OptionsBase.maxEntrySize}\n   */\n  maxEntrySize: LRUCache.Size\n  /**\n   * {@link LRUCache.OptionsBase.sizeCalculation}\n   */\n  sizeCalculation?: LRUCache.SizeCalculator\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n   */\n  noDeleteOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n   */\n  noDeleteOnStaleGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n   */\n  allowStaleOnFetchAbort: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n   */\n  allowStaleOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n   */\n  ignoreFetchAbort: boolean\n\n  /** {@link LRUCache.OptionsBase.backgroundFetchSize} */\n  backgroundFetchSize: number\n\n  // computed properties\n  #size: LRUCache.Count\n  #calculatedSize: LRUCache.Size\n  #keyMap: Map\n  #keyList: (K | undefined)[]\n  #valList: (V | BackgroundFetch | undefined)[]\n  #next: NumberArray\n  #prev: NumberArray\n  #head: Index\n  #tail: Index\n  #free: StackLike\n  #disposed?: DisposeTask[]\n  #sizes?: ZeroArray\n  #starts?: ZeroArray\n  #ttls?: ZeroArray\n  #autopurgeTimers?: (undefined | ReturnType)[]\n\n  #hasDispose: boolean\n  #hasFetchMethod: boolean\n  #hasDisposeAfter: boolean\n  #hasOnInsert: boolean\n\n  /**\n   * Do not call this method unless you need to inspect the\n   * inner workings of the cache.  If anything returned by this\n   * object is modified in any way, strange breakage may occur.\n   *\n   * These fields are private for a reason!\n   *\n   * @internal\n   */\n  static unsafeExposeInternals<\n    K extends {},\n    V extends {},\n    FC extends unknown = unknown,\n  >(c: LRUCache) {\n    return {\n      // properties\n      starts: c.#starts,\n      ttls: c.#ttls,\n      autopurgeTimers: c.#autopurgeTimers,\n      sizes: c.#sizes,\n      keyMap: c.#keyMap as Map,\n      keyList: c.#keyList,\n      valList: c.#valList,\n      next: c.#next,\n      prev: c.#prev,\n      get head() {\n        return c.#head\n      },\n      get tail() {\n        return c.#tail\n      },\n      free: c.#free,\n      // methods\n      isBackgroundFetch: (p: unknown) => c.#isBackgroundFetch(p),\n      backgroundFetch: (\n        k: K,\n        index: number | undefined,\n        options: LRUCache.FetchOptions,\n        context: unknown,\n      ): BackgroundFetch =>\n        c.#backgroundFetch(\n          k,\n          index as Index | undefined,\n          options,\n          context as FC,\n        ),\n      moveToTail: (index: number): void => c.#moveToTail(index as Index),\n      indexes: (options?: { allowStale: boolean }) => c.#indexes(options),\n      rindexes: (options?: { allowStale: boolean }) =>\n        c.#rindexes(options),\n      isStale: (index: number | undefined) => c.#isStale(index as Index),\n    }\n  }\n\n  // Protected read-only members\n\n  /**\n   * {@link LRUCache.OptionsBase.max} (read-only)\n   */\n  get max(): LRUCache.Count {\n    return this.#max\n  }\n  /**\n   * {@link LRUCache.OptionsBase.maxSize} (read-only)\n   */\n  get maxSize(): LRUCache.Count {\n    return this.#maxSize\n  }\n  /**\n   * The total computed size of items in the cache (read-only)\n   */\n  get calculatedSize(): LRUCache.Size {\n    return this.#calculatedSize\n  }\n  /**\n   * The number of items stored in the cache (read-only)\n   */\n  get size(): LRUCache.Count {\n    return this.#size\n  }\n  /**\n   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n   */\n  get fetchMethod(): LRUCache.Fetcher | undefined {\n    return this.#fetchMethod\n  }\n  get memoMethod(): LRUCache.Memoizer | undefined {\n    return this.#memoMethod\n  }\n  /**\n   * {@link LRUCache.OptionsBase.dispose} (read-only)\n   */\n  get dispose() {\n    return this.#dispose\n  }\n  /**\n   * {@link LRUCache.OptionsBase.onInsert} (read-only)\n   */\n  get onInsert() {\n    return this.#onInsert\n  }\n  /**\n   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n   */\n  get disposeAfter() {\n    return this.#disposeAfter\n  }\n\n  constructor(options: LRUCache.Options | LRUCache) {\n    const {\n      max = 0,\n      ttl,\n      ttlResolution = 1,\n      ttlAutopurge,\n      updateAgeOnGet,\n      updateAgeOnHas,\n      allowStale,\n      dispose,\n      onInsert,\n      disposeAfter,\n      noDisposeOnSet,\n      noUpdateTTL,\n      maxSize = 0,\n      maxEntrySize = 0,\n      sizeCalculation,\n      fetchMethod,\n      memoMethod,\n      noDeleteOnFetchRejection,\n      noDeleteOnStaleGet,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      backgroundFetchSize = 1,\n      perf,\n    } = options\n\n    this.backgroundFetchSize = backgroundFetchSize\n\n    if (perf !== undefined) {\n      if (typeof perf?.now !== 'function') {\n        throw new TypeError(\n          'perf option must have a now() method if specified',\n        )\n      }\n    }\n\n    this.#perf = perf ?? defaultPerf\n\n    if (max !== 0 && !isPosInt(max)) {\n      throw new TypeError('max option must be a nonnegative integer')\n    }\n\n    const UintArray = max ? getUintArray(max) : Array\n    if (!UintArray) {\n      throw new Error('invalid max value: ' + max)\n    }\n\n    this.#max = max\n    this.#maxSize = maxSize\n    this.maxEntrySize = maxEntrySize || this.#maxSize\n    this.sizeCalculation = sizeCalculation\n    if (this.sizeCalculation) {\n      if (!this.#maxSize && !this.maxEntrySize) {\n        throw new TypeError(\n          'cannot set sizeCalculation without setting maxSize or maxEntrySize',\n        )\n      }\n      if (typeof this.sizeCalculation !== 'function') {\n        throw new TypeError('sizeCalculation set to non-function')\n      }\n    }\n\n    if (memoMethod !== undefined && typeof memoMethod !== 'function') {\n      throw new TypeError('memoMethod must be a function if defined')\n    }\n    this.#memoMethod = memoMethod\n\n    if (fetchMethod !== undefined && typeof fetchMethod !== 'function') {\n      throw new TypeError('fetchMethod must be a function if specified')\n    }\n    this.#fetchMethod = fetchMethod\n    this.#hasFetchMethod = !!fetchMethod\n\n    this.#keyMap = new Map()\n    this.#keyList = Array.from({ length: max }).fill(undefined) as (\n      | K\n      | undefined\n    )[]\n    this.#valList = Array.from({ length: max }).fill(undefined) as (\n      | V\n      | undefined\n    )[]\n    this.#next = new UintArray(max)\n    this.#prev = new UintArray(max)\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free = Stack.create(max)\n    this.#size = 0\n    this.#calculatedSize = 0\n\n    if (typeof dispose === 'function') {\n      this.#dispose = dispose\n    }\n    if (typeof onInsert === 'function') {\n      this.#onInsert = onInsert\n    }\n    if (typeof disposeAfter === 'function') {\n      this.#disposeAfter = disposeAfter\n      this.#disposed = []\n    } else {\n      this.#disposeAfter = undefined\n      this.#disposed = undefined\n    }\n    this.#hasDispose = !!this.#dispose\n    this.#hasOnInsert = !!this.#onInsert\n    this.#hasDisposeAfter = !!this.#disposeAfter\n\n    this.noDisposeOnSet = !!noDisposeOnSet\n    this.noUpdateTTL = !!noUpdateTTL\n    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n    this.ignoreFetchAbort = !!ignoreFetchAbort\n\n    // NB: maxEntrySize is set to maxSize if it's set\n    if (this.maxEntrySize !== 0) {\n      if (this.#maxSize !== 0) {\n        if (!isPosInt(this.#maxSize)) {\n          throw new TypeError(\n            'maxSize must be a positive integer if specified',\n          )\n        }\n      }\n      if (!isPosInt(this.maxEntrySize)) {\n        throw new TypeError(\n          'maxEntrySize must be a positive integer if specified',\n        )\n      }\n      this.#initializeSizeTracking()\n    }\n\n    this.allowStale = !!allowStale\n    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n    this.updateAgeOnGet = !!updateAgeOnGet\n    this.updateAgeOnHas = !!updateAgeOnHas\n    this.ttlResolution =\n      isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1\n    this.ttlAutopurge = !!ttlAutopurge\n    this.ttl = ttl || 0\n    if (this.ttl) {\n      if (!isPosInt(this.ttl)) {\n        throw new TypeError('ttl must be a positive integer if specified')\n      }\n      this.#initializeTTLTracking()\n    }\n\n    // do not allow completely unbounded caches\n    if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n      throw new TypeError(\n        'At least one of max, maxSize, or ttl is required',\n      )\n    }\n    if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n      const code = 'LRU_CACHE_UNBOUNDED'\n      if (shouldWarn(code)) {\n        warned.add(code)\n        const msg =\n          'TTL caching without ttlAutopurge, max, or maxSize can ' +\n          'result in unbounded memory consumption.'\n        emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n      }\n    }\n  }\n\n  /**\n   * Return the number of ms left in the item's TTL. If item is not in cache,\n   * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n   */\n  getRemainingTTL(key: K) {\n    return this.#keyMap.has(key) ? Infinity : 0\n  }\n\n  #initializeTTLTracking() {\n    const ttls = new ZeroArray(this.#max)\n    const starts = new ZeroArray(this.#max)\n    this.#ttls = ttls\n    this.#starts = starts\n    const purgeTimers =\n      this.ttlAutopurge ?\n        Array.from>({\n          length: this.#max,\n        })\n      : undefined\n    this.#autopurgeTimers = purgeTimers\n\n    this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {\n      starts[index] = ttl !== 0 ? start : 0\n      ttls[index] = ttl\n      setPurgeTimer(index, ttl)\n    }\n\n    this.#updateItemAge = index => {\n      starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0\n      setPurgeTimer(index, ttls[index])\n    }\n\n    // clear out the purge timer if we're setting TTL to 0, and\n    // previously had a ttl purge timer running, so it doesn't\n    // fire unnecessarily. Don't need to do this if we're not doing\n    // autopurge.\n    const setPurgeTimer =\n      !this.ttlAutopurge ?\n        () => {}\n      : (index: Index, ttl?: number) => {\n          if (purgeTimers?.[index]) {\n            clearTimeout(purgeTimers[index])\n            purgeTimers[index] = undefined\n          }\n          if (ttl && ttl !== 0 && purgeTimers) {\n            const t = setTimeout(() => {\n              if (this.#isStale(index)) {\n                this.#delete(this.#keyList[index] as K, 'expire')\n                purgeTimers[index] = undefined\n              } else {\n                setPurgeTimer(index, getRemainingTTL(index))\n              }\n            }, ttl + 1)\n            // unref() not supported on all platforms\n            /* c8 ignore start */\n            if (t.unref) {\n              t.unref()\n            }\n            /* c8 ignore stop */\n            purgeTimers[index] = t\n          }\n        }\n\n    this.#statusTTL = (status, index) => {\n      if (ttls[index]) {\n        const ttl = ttls[index]\n        const start = starts[index]\n        /* c8 ignore start */\n        if (!ttl || !start) {\n          return\n        }\n        /* c8 ignore stop */\n        status.ttl = ttl\n        status.start = start\n        status.now = cachedNow || getNow()\n        const age = status.now - start\n        status.remainingTTL = ttl - age\n      }\n    }\n\n    // debounce calls to perf.now() to 1s so we're not hitting\n    // that costly call repeatedly.\n    let cachedNow = 0\n    const getNow = () => {\n      const n = this.#perf.now()\n      if (this.ttlResolution > 0) {\n        cachedNow = n\n        const t = setTimeout(() => (cachedNow = 0), this.ttlResolution)\n        // not available on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n      return n\n    }\n\n    this.getRemainingTTL = key => {\n      const index = this.#keyMap.get(key)\n      if (index === undefined) {\n        return 0\n      }\n      return getRemainingTTL(index)\n    }\n    const getRemainingTTL = (index: Index) => {\n      const ttl = ttls[index]\n      const start = starts[index]\n      if (!ttl || !start) {\n        return Infinity\n      }\n      const age = (cachedNow || getNow()) - start\n      return ttl - age\n    }\n\n    this.#isStale = index => {\n      const s = starts[index]\n      const t = ttls[index]\n      return !!t && !!s && (cachedNow || getNow()) - s > t\n    }\n  }\n\n  // conditionally set private methods related to TTL\n  #updateItemAge: (index: Index) => void = () => {}\n  #statusTTL: (status: LRUCache.Status, index: Index) => void =\n    () => {}\n  #setItemTTL: (\n    index: Index,\n    ttl: LRUCache.Milliseconds,\n    start?: LRUCache.Milliseconds,\n    // ignore because we never call this if we're not already in TTL mode\n    /* c8 ignore start */\n  ) => void = () => {}\n  /* c8 ignore stop */\n\n  #isStale: (index: Index) => boolean = () => false\n\n  #initializeSizeTracking() {\n    const sizes = new ZeroArray(this.#max)\n    this.#calculatedSize = 0\n    this.#sizes = sizes\n    this.#removeItemSize = index => {\n      this.#calculatedSize -= sizes[index] as number\n      sizes[index] = 0\n    }\n    this.#requireSize = (k, v, size, sizeCalculation) => {\n      if (!isPosInt(size)) {\n        // provisionally accept background fetches.\n        // actual value size will be checked when they return.\n        if (this.#isBackgroundFetch(v)) {\n          // NB: this cannot occur if v.__staleWhileFetching is set,\n          // because in that case, it would take on the size of the\n          // existing entry that it temporarily replaces.\n          return this.backgroundFetchSize\n        }\n        if (sizeCalculation) {\n          if (typeof sizeCalculation !== 'function') {\n            throw new TypeError('sizeCalculation must be a function')\n          }\n          size = sizeCalculation(v, k)\n          if (!isPosInt(size)) {\n            throw new TypeError(\n              'sizeCalculation return invalid (expect positive integer)',\n            )\n          }\n        } else {\n          throw new TypeError(\n            'invalid size value (must be positive integer). ' +\n              'When maxSize or maxEntrySize is used, sizeCalculation ' +\n              'or size must be set.',\n          )\n        }\n      }\n      return size\n    }\n\n    this.#addItemSize = (\n      index: Index,\n      size: LRUCache.Size,\n      status?: LRUCache.Status,\n    ) => {\n      sizes[index] = size\n      if (this.#maxSize) {\n        const maxSize = this.#maxSize - sizes[index]\n        while (this.#calculatedSize > maxSize) {\n          this.#evict(true)\n        }\n      }\n      this.#calculatedSize += sizes[index]\n      if (status) {\n        status.entrySize = size\n        status.totalCalculatedSize = this.#calculatedSize\n      }\n    }\n  }\n\n  #removeItemSize: (index: Index) => void = _i => {}\n\n  #addItemSize: (\n    index: Index,\n    size: LRUCache.Size,\n    status?: LRUCache.Status,\n  ) => void = (_i, _s, _st) => {}\n\n  #requireSize: (\n    k: K,\n    v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator,\n    status?: LRUCache.Status,\n  ) => LRUCache.Size = (\n    _k: K,\n    _v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator,\n  ) => {\n    if (size || sizeCalculation) {\n      throw new TypeError(\n        'cannot set size without setting maxSize or maxEntrySize on cache',\n      )\n    }\n    return 0\n  };\n\n  *#indexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#tail; this.#isValidIndex(i); ) {\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#head) {\n          break\n        } else {\n          i = this.#prev[i] as Index\n        }\n      }\n    }\n  }\n\n  *#rindexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#head; this.#isValidIndex(i); ) {\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#tail) {\n          break\n        } else {\n          i = this.#next[i] as Index\n        }\n      }\n    }\n  }\n\n  #isValidIndex(index: Index) {\n    return (\n      index !== undefined &&\n      this.#keyMap.get(this.#keyList[index] as K) === index\n    )\n  }\n\n  /**\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from most recently used to least recently used.\n   */\n  *entries() {\n    for (const i of this.#indexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]] as [K, V]\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.entries}\n   *\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from least recently used to most recently used.\n   */\n  *rentries() {\n    for (const i of this.#rindexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]]\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the keys in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *keys() {\n    for (const i of this.#indexes()) {\n      const k = this.#keyList[i]\n      if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.keys}\n   *\n   * Return a generator yielding the keys in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rkeys() {\n    for (const i of this.#rindexes()) {\n      const k = this.#keyList[i]\n      if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the values in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *values() {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield this.#valList[i] as V\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.values}\n   *\n   * Return a generator yielding the values in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rvalues() {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) {\n        yield this.#valList[i]\n      }\n    }\n  }\n\n  /**\n   * Iterating over the cache itself yields the same results as\n   * {@link LRUCache.entries}\n   */\n  [Symbol.iterator]() {\n    return this.entries()\n  }\n\n  /**\n   * A String value that is used in the creation of the default string\n   * description of an object. Called by the built-in method\n   * `Object.prototype.toString`.\n   */\n  [Symbol.toStringTag] = 'LRUCache'\n\n  /**\n   * Find a value for which the supplied fn method returns a truthy value,\n   * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n   */\n  find(\n    fn: (v: V, k: K, self: LRUCache) => boolean,\n    getOptions: LRUCache.GetOptions = {},\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      if (fn(value, this.#keyList[i] as K, this)) {\n        return this.#get(this.#keyList[i] as K, getOptions)\n      }\n    }\n  }\n\n  /**\n   * Call the supplied function on each item in the cache, in order from most\n   * recently used to least recently used.\n   *\n   * `fn` is called as `fn(value, key, cache)`.\n   *\n   * If `thisp` is provided, function will be called in the `this`-context of\n   * the provided object, or the cache if no `thisp` object is provided.\n   *\n   * Does not update age or recenty of use, or iterate over stale values.\n   */\n  forEach(\n    fn: (v: V, k: K, self: LRUCache) => unknown,\n    thisp: unknown = this,\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * The same as {@link LRUCache.forEach} but items are iterated over in\n   * reverse order.  (ie, less recently used items are iterated over first.)\n   */\n  rforEach(\n    fn: (v: V, k: K, self: LRUCache) => unknown,\n    thisp: unknown = this,\n  ) {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * Delete any stale entries. Returns true if anything was removed,\n   * false otherwise.\n   */\n  purgeStale() {\n    let deleted = false\n    for (const i of this.#rindexes({ allowStale: true })) {\n      if (this.#isStale(i)) {\n        this.#delete(this.#keyList[i] as K, 'expire')\n        deleted = true\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Get the extended info about a given entry, to get its value, size, and\n   * TTL info simultaneously. Returns `undefined` if the key is not present.\n   *\n   * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n   * serialization, the `start` value is always the current timestamp, and the\n   * `ttl` is a calculated remaining time to live (negative if expired).\n   *\n   * Always returns stale values, if their info is found in the cache, so be\n   * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n   * if relevant.\n   */\n  info(key: K): LRUCache.Entry | undefined {\n    const i = this.#keyMap.get(key)\n    if (i === undefined) return undefined\n    const v = this.#valList[i]\n    /* c8 ignore start - this isn't tested for the info function,\n     * but it's the same logic as found in other places. */\n    const value: V | undefined =\n      this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n    if (value === undefined) return undefined\n    /* c8 ignore stop */\n    const entry: LRUCache.Entry = { value }\n    if (this.#ttls && this.#starts) {\n      const ttl = this.#ttls[i]\n      const start = this.#starts[i]\n      if (ttl && start) {\n        const remain = ttl - (this.#perf.now() - start)\n        entry.ttl = remain\n        entry.start = Date.now()\n      }\n    }\n    if (this.#sizes) {\n      entry.size = this.#sizes[i]\n    }\n    return entry\n  }\n\n  /**\n   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n   * passed to {@link LRUCache#load}.\n   *\n   * The `start` fields are calculated relative to a portable `Date.now()`\n   * timestamp, even if `performance.now()` is available.\n   *\n   * Stale entries are always included in the `dump`, even if\n   * {@link LRUCache.OptionsBase.allowStale} is false.\n   *\n   * Note: this returns an actual array, not a generator, so it can be more\n   * easily passed around.\n   */\n  dump() {\n    const arr: [K, LRUCache.Entry][] = []\n    for (const i of this.#indexes({ allowStale: true })) {\n      const key = this.#keyList[i]\n      const v = this.#valList[i]\n      const value: V | undefined =\n        this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n      if (value === undefined || key === undefined) continue\n      const entry: LRUCache.Entry = { value }\n      if (this.#ttls && this.#starts) {\n        entry.ttl = this.#ttls[i]\n        // always dump the start relative to a portable timestamp\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = this.#perf.now() - (this.#starts[i] as number)\n        entry.start = Math.floor(Date.now() - age)\n      }\n      if (this.#sizes) {\n        entry.size = this.#sizes[i]\n      }\n      arr.unshift([key, entry])\n    }\n    return arr\n  }\n\n  /**\n   * Reset the cache and load in the items in entries in the order listed.\n   *\n   * The shape of the resulting cache may be different if the same options are\n   * not used in both caches.\n   *\n   * The `start` fields are assumed to be calculated relative to a portable\n   * `Date.now()` timestamp, even if `performance.now()` is available.\n   */\n  load(arr: [K, LRUCache.Entry][]) {\n    this.clear()\n    for (const [key, entry] of arr) {\n      if (entry.start) {\n        // entry.start is a portable timestamp, but we may be using\n        // node's performance.now(), so calculate the offset, so that\n        // we get the intended remaining TTL, no matter how long it's\n        // been on ice.\n        //\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = Date.now() - entry.start\n        entry.start = this.#perf.now() - age\n      }\n      this.#set(key, entry.value, entry)\n    }\n  }\n\n  /**\n   * Add a value to the cache.\n   *\n   * Note: if `undefined` is specified as a value, this is an alias for\n   * {@link LRUCache#delete}\n   *\n   * Fields on the {@link LRUCache.SetOptions} options param will override\n   * their corresponding values in the constructor options for the scope\n   * of this single `set()` operation.\n   *\n   * If `start` is provided, then that will set the effective start\n   * time for the TTL calculation. Note that this must be a previous\n   * value of `performance.now()` if supported, or a previous value of\n   * `Date.now()` if not.\n   *\n   * Options object may also include `size`, which will prevent\n   * calling the `sizeCalculation` function and just use the specified\n   * number if it is a positive integer, and `noDisposeOnSet` which\n   * will prevent calling a `dispose` function in the case of\n   * overwrites.\n   *\n   * If the `size` (or return value of `sizeCalculation`) for a given\n   * entry is greater than `maxEntrySize`, then the item will not be\n   * added to the cache.\n   *\n   * Will update the recency of the entry.\n   *\n   * If the value is `undefined`, then this is an alias for\n   * `cache.delete(key)`. `undefined` is never stored in the cache.\n   */\n  set(\n    k: K,\n    v: V | undefined,\n    setOptions: LRUCache.SetOptions = {},\n  ) {\n    const { status = metrics.hasSubscribers ? {} : undefined } = setOptions\n    setOptions.status = status\n    if (status) {\n      status.op = 'set'\n      status.key = k\n      if (v !== undefined) status.value = v\n      status.cache = this\n    }\n    const result = this.#set(k, v, setOptions)\n    if (status && metrics.hasSubscribers) {\n      metrics.publish(status)\n    }\n    return result\n  }\n\n  #set(\n    k: K,\n    v: V | BackgroundFetch | undefined,\n    setOptions: LRUCache.SetOptions,\n    bf?: BackgroundFetch,\n  ) {\n    const {\n      ttl = this.ttl,\n      start,\n      noDisposeOnSet = this.noDisposeOnSet,\n      sizeCalculation = this.sizeCalculation,\n      status,\n    } = setOptions\n\n    const isBF = this.#isBackgroundFetch(v)\n    if (v === undefined) {\n      if (status) status.set = 'deleted'\n      this.delete(k)\n      return this\n    }\n    let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n    if (status && !isBF) status.value = v\n\n    const size = this.#requireSize(\n      k,\n      v,\n      setOptions.size || 0,\n      sizeCalculation,\n      status,\n    )\n    // if the item doesn't fit, don't do anything\n    // NB: maxEntrySize set to maxSize by default\n    if (this.maxEntrySize && size > this.maxEntrySize) {\n      // have to delete, in case something is there already.\n      this.#delete(k, 'set')\n      if (status) {\n        status.set = 'miss'\n        status.maxEntrySizeExceeded = true\n      }\n      return this\n    }\n    let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n    if (index === undefined) {\n      // addition\n      index = (\n        this.#size === 0 ? this.#tail\n        : this.#free.length !== 0 ? this.#free.pop()\n        : this.#size === this.#max ? this.#evict(false)\n        : this.#size) as Index\n      this.#keyList[index] = k\n      this.#valList[index] = v\n      this.#keyMap.set(k, index)\n      this.#next[this.#tail] = index\n      this.#prev[index] = this.#tail\n      this.#tail = index\n      this.#size++\n      this.#addItemSize(index, size, status)\n      if (status) status.set = 'add'\n      noUpdateTTL = false\n      if (this.#hasOnInsert && !isBF) {\n        this.#onInsert?.(v, k, 'add')\n      }\n    } else {\n      // update\n      // might be updating a background fetch!\n      this.#moveToTail(index)\n      const oldVal = this.#valList[index]!\n      if (v !== oldVal) {\n        if (!noDisposeOnSet) {\n          if (this.#isBackgroundFetch(oldVal)) {\n            if (oldVal !== bf) {\n              // setting over a background fetch, not merely resolving it.\n              oldVal.__abortController.abort(new Error('replaced'))\n            }\n            const { __staleWhileFetching: s } = oldVal\n            if (s !== undefined && s !== v) {\n              if (this.#hasDispose) {\n                this.#dispose?.(s, k, 'set')\n              }\n              if (this.#hasDisposeAfter) {\n                this.#disposed?.push([s, k, 'set'])\n              }\n            }\n          } else {\n            if (this.#hasDispose) {\n              this.#dispose?.(oldVal, k, 'set')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([oldVal, k, 'set'])\n            }\n          }\n        }\n        this.#removeItemSize(index)\n        this.#addItemSize(index, size, status)\n        this.#valList[index] = v\n        if (!isBF) {\n          const oldValue =\n            oldVal && this.#isBackgroundFetch(oldVal) ?\n              oldVal.__staleWhileFetching\n            : oldVal\n          const setType =\n            oldValue === undefined ? 'add'\n            : v !== oldValue ? 'replace'\n            : 'update'\n          if (status) {\n            status.set = setType\n            if (oldValue !== undefined) status.oldValue = oldValue\n          }\n          if (this.#hasOnInsert) {\n            this.onInsert?.(v, k, setType)\n          }\n        }\n      } else if (!isBF) {\n        if (status) {\n          status.set = 'update'\n        }\n        if (this.#hasOnInsert) {\n          this.onInsert?.(v, k, 'update')\n        }\n      }\n    }\n    if (ttl !== 0 && !this.#ttls) {\n      this.#initializeTTLTracking()\n    }\n    if (this.#ttls) {\n      if (!noUpdateTTL) {\n        this.#setItemTTL(index, ttl, start)\n      }\n      if (status) this.#statusTTL(status, index)\n    }\n    if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return this\n  }\n\n  /**\n   * Evict the least recently used item, returning its value or\n   * `undefined` if cache is empty.\n   */\n  pop(): V | undefined {\n    try {\n      while (this.#size) {\n        const val = this.#valList[this.#head]\n        this.#evict(true)\n        if (this.#isBackgroundFetch(val)) {\n          if (val.__staleWhileFetching) {\n            return val.__staleWhileFetching\n          }\n        } else if (val !== undefined) {\n          return val\n        }\n      }\n    } finally {\n      if (this.#hasDisposeAfter && this.#disposed) {\n        const dt = this.#disposed\n        let task: DisposeTask | undefined\n        while ((task = dt?.shift())) {\n          this.#disposeAfter?.(...task)\n        }\n      }\n    }\n  }\n\n  #evict(free: boolean) {\n    const head = this.#head\n    const k = this.#keyList[head]!\n    const v = this.#valList[head]!\n    const isBF = this.#isBackgroundFetch(v)\n    if (isBF) {\n      v.__abortController.abort(new Error('evicted'))\n    }\n    const oldValue = isBF ? v.__staleWhileFetching : v\n    if (\n      (this.#hasDispose || this.#hasDisposeAfter) &&\n      oldValue !== undefined\n    ) {\n      if (this.#hasDispose) {\n        this.#dispose?.(oldValue, k, 'evict')\n      }\n      if (this.#hasDisposeAfter) {\n        this.#disposed?.push([oldValue, k, 'evict'])\n      }\n    }\n    this.#removeItemSize(head)\n    if (this.#autopurgeTimers?.[head]) {\n      clearTimeout(this.#autopurgeTimers[head])\n      this.#autopurgeTimers[head] = undefined\n    }\n    // if we aren't about to use the index, then null these out\n    if (free) {\n      this.#keyList[head] = undefined\n      this.#valList[head] = undefined\n      this.#free.push(head)\n    }\n    if (this.#size === 1) {\n      this.#head = this.#tail = 0 as Index\n      this.#free.length = 0\n    } else {\n      this.#head = this.#next[head] as Index\n    }\n    this.#keyMap.delete(k)\n    this.#size--\n    return head\n  }\n\n  /**\n   * Check if a key is in the cache, without updating the recency of use.\n   * Will return false if the item is stale, even though it is technically\n   * in the cache.\n   *\n   * Check if a key is in the cache, without updating the recency of\n   * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n   * to `true` in either the options or the constructor.\n   *\n   * Will return `false` if the item is stale, even though it is technically in\n   * the cache. The difference can be determined (if it matters) by using a\n   * `status` argument, and inspecting the `has` field.\n   *\n   * Will not update item age unless\n   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n   */\n  has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { status = metrics.hasSubscribers ? {} : undefined } = hasOptions\n    hasOptions.status = status\n    if (status) {\n      status.op = 'has'\n      status.key = k\n      status.cache = this\n    }\n    const result = this.#has(k, hasOptions)\n    if (metrics.hasSubscribers) metrics.publish(status)\n    return result\n  }\n  #has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const v = this.#valList[index]\n      if (\n        this.#isBackgroundFetch(v) &&\n        v.__staleWhileFetching === undefined\n      ) {\n        return false\n      }\n      if (!this.#isStale(index)) {\n        if (updateAgeOnHas) {\n          this.#updateItemAge(index)\n        }\n        if (status) {\n          status.has = 'hit'\n          this.#statusTTL(status, index)\n        }\n        return true\n      } else if (status) {\n        status.has = 'stale'\n        this.#statusTTL(status, index)\n      }\n    } else if (status) {\n      status.has = 'miss'\n    }\n    return false\n  }\n\n  /**\n   * Like {@link LRUCache#get} but doesn't update recency or delete stale\n   * items.\n   *\n   * Returns `undefined` if the item is stale, unless\n   * {@link LRUCache.OptionsBase.allowStale} is set.\n   */\n  peek(k: K, peekOptions: LRUCache.PeekOptions = {}) {\n    const { status = hasSubscribers() ? {} : undefined } = peekOptions\n    if (status) {\n      status.op = 'peek'\n      status.key = k\n      status.cache = this\n    }\n    peekOptions.status = status\n    const result = this.#peek(k, peekOptions)\n    if (metrics.hasSubscribers) {\n      metrics.publish(status)\n    }\n    return result\n  }\n  #peek(k: K, peekOptions: LRUCache.PeekOptions) {\n    const { status, allowStale = this.allowStale } = peekOptions\n    const index = this.#keyMap.get(k)\n    if (index === undefined || (!allowStale && this.#isStale(index))) {\n      if (status) status.peek = index === undefined ? 'miss' : 'stale'\n      return undefined\n    }\n    const v = this.#valList[index]\n    const val = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n    if (status) {\n      if (val !== undefined) {\n        status.peek = 'hit'\n        status.value = val\n      } else {\n        status.peek = 'miss'\n      }\n    }\n    return val\n  }\n\n  #backgroundFetch(\n    k: K,\n    index: Index | undefined,\n    options: LRUCache.FetchOptions,\n    context: FC,\n  ): BackgroundFetch {\n    const v = index === undefined ? undefined : this.#valList[index]\n    if (this.#isBackgroundFetch(v)) {\n      return v\n    }\n\n    const ac = new AbortController()\n    const { signal } = options\n    // when/if our AC signals, then stop listening to theirs.\n    signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n      signal: ac.signal,\n    })\n\n    const fetchOpts = {\n      signal: ac.signal,\n      options,\n      context,\n    }\n\n    const cb = (v: V | undefined, updateCache = false): V | undefined => {\n      const { aborted } = ac.signal\n      const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n      const proceed =\n        options.ignoreFetchAbort ||\n        !!(options.allowStaleOnFetchAbort && v !== undefined)\n      if (options.status) {\n        if (aborted && !updateCache) {\n          options.status.fetchAborted = true\n          options.status.fetchError = ac.signal.reason\n          if (ignoreAbort) options.status.fetchAbortIgnored = true\n        } else {\n          options.status.fetchResolved = true\n        }\n      }\n      if (aborted && !ignoreAbort && !updateCache) {\n        return fetchFail(ac.signal.reason, proceed)\n      }\n      // either we didn't abort, and are still here, or we did, and ignored\n      const bf = p as BackgroundFetch\n      // if nothing else has been written there but we're set to update the\n      // cache and ignore the abort, or if it's still pending on this specific\n      // background request, then write it to the cache.\n      const vl = this.#valList[index as Index]\n      if (vl === p || (vl === undefined && ignoreAbort && updateCache)) {\n        if (v === undefined) {\n          if (bf.__staleWhileFetching !== undefined) {\n            this.#valList[index as Index] = bf.__staleWhileFetching\n          } else {\n            this.#delete(k, 'fetch')\n          }\n        } else {\n          if (options.status) options.status.fetchUpdated = true\n          this.#set(k, v, fetchOpts.options, bf)\n        }\n      }\n      return v\n    }\n\n    const eb = (er: unknown) => {\n      if (options.status) {\n        options.status.fetchRejected = true\n        options.status.fetchError = er as Error\n      }\n      // do not pass go, do not collect $200\n      return fetchFail(er, false)\n    }\n\n    const fetchFail = (er: unknown, proceed: boolean): V | undefined => {\n      const { aborted } = ac.signal\n      const allowStaleAborted = aborted && options.allowStaleOnFetchAbort\n      const allowStale =\n        allowStaleAborted || options.allowStaleOnFetchRejection\n      const noDelete = allowStale || options.noDeleteOnFetchRejection\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        // if we allow stale on fetch rejections, then we need to ensure that\n        // the stale value is not removed from the cache when the fetch fails.\n        const del =\n          !noDelete || (!proceed && bf.__staleWhileFetching === undefined)\n        if (del) {\n          this.#delete(k, 'fetch')\n        } else if (!allowStaleAborted) {\n          // still replace the *promise* with the stale value,\n          // since we are done with the promise at this point.\n          // leave it untouched if we're still waiting for an\n          // aborted background fetch that hasn't yet returned.\n          this.#valList[index as Index] = bf.__staleWhileFetching\n        }\n      }\n      if (allowStale) {\n        if (options.status && bf.__staleWhileFetching !== undefined) {\n          options.status.returnedStale = true\n        }\n        return bf.__staleWhileFetching\n      } else if (bf.__returned === bf) {\n        throw er\n      }\n    }\n\n    const pcall = (\n      res: (v: V | undefined) => void,\n      rej: (e: unknown) => void,\n    ) => {\n      const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n      // ignored, we go until we finish, regardless.\n      // defer check until we are actually aborting,\n      // so fetchMethod can override.\n      ac.signal.addEventListener('abort', () => {\n        if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {\n          res(undefined)\n          // when it eventually resolves, update the cache.\n          if (options.allowStaleOnFetchAbort) {\n            res = v => cb(v, true)\n          }\n        }\n      })\n      if (fmp && fmp instanceof Promise) {\n        fmp.then(v => res(v === undefined ? undefined : v), rej)\n      } else if (fmp !== undefined) {\n        res(fmp)\n      }\n    }\n\n    if (options.status) options.status.fetchDispatched = true\n    const p = new Promise(pcall).then(cb, eb)\n    const bf: BackgroundFetch = Object.assign(p, {\n      __abortController: ac,\n      __staleWhileFetching: v,\n      __returned: undefined,\n    })\n\n    if (index === undefined) {\n      // internal, don't expose status.\n      this.#set(k, bf, { ...fetchOpts.options, status: undefined })\n      index = this.#keyMap.get(k)\n    } else {\n      // do not call #set, because we do not want to adjust its place\n      // in the lru queue, as it has not yet been \"used\". Also, we don't\n      // need to worry about evicting for size, because a background fetch\n      // over a stale value is treated as the same size as its stale value.\n      this.#valList[index] = bf\n    }\n    return bf\n  }\n\n  #isBackgroundFetch(p: unknown): p is BackgroundFetch {\n    if (!this.#hasFetchMethod) return false\n    const b = p as BackgroundFetch\n    return (\n      !!b &&\n      b instanceof Promise &&\n      b.hasOwnProperty('__staleWhileFetching') &&\n      b.__abortController instanceof AbortController\n    )\n  }\n\n  /**\n   * Make an asynchronous cached fetch using the\n   * {@link LRUCache.OptionsBase.fetchMethod} function.\n   *\n   * If the value is in the cache and not stale, then the returned\n   * Promise resolves to the value.\n   *\n   * If not in the cache, or beyond its TTL staleness, then\n   * `fetchMethod(key, staleValue, { options, signal, context })` is\n   * called, and the value returned will be added to the cache once\n   * resolved.\n   *\n   * If called with `allowStale`, and an asynchronous fetch is\n   * currently in progress to reload a stale value, then the former\n   * stale value will be returned.\n   *\n   * If called with `forceRefresh`, then the cached item will be\n   * re-fetched, even if it is not stale. However, if `allowStale` is also\n   * set, then the old value will still be returned. This is useful\n   * in cases where you want to force a reload of a cached value. If\n   * a background fetch is already in progress, then `forceRefresh`\n   * has no effect.\n   *\n   * If multiple fetches for the same key are issued, then they will all be\n   * coalesced into a single call to fetchMethod.\n   *\n   * Note that this means that handling options such as\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n   * {@link LRUCache.FetchOptions.signal},\n   * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n   * determined by the FIRST fetch() call for a given key.\n   *\n   * This is a known (fixable) shortcoming which will be addresed on when\n   * someone complains about it, as the fix would involve added complexity and\n   * may not be worth the costs for this edge case.\n   *\n   * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n   * effectively an alias for `Promise.resolve(cache.get(key))`.\n   *\n   * When the fetch method resolves to a value, if the fetch has not\n   * been aborted due to deletion, eviction, or being overwritten,\n   * then it is added to the cache using the options provided.\n   *\n   * If the key is evicted or deleted before the `fetchMethod`\n   * resolves, then the AbortSignal passed to the `fetchMethod` will\n   * receive an `abort` event, and the promise returned by `fetch()`\n   * will reject with the reason for the abort.\n   *\n   * If a `signal` is passed to the `fetch()` call, then aborting the\n   * signal will abort the fetch and cause the `fetch()` promise to\n   * reject with the reason provided.\n   *\n   * **Setting `context`**\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the {@link LRUCache} constructor, then all\n   * calls to `cache.fetch()` _must_ provide a `context` option. If\n   * set to `undefined` or `void`, then calls to fetch _must not_\n   * provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that\n   * might be relevant in the course of fetching the data. It is only\n   * relevant for the course of a single `fetch()` operation, and\n   * discarded afterwards.\n   *\n   * **Note: `fetch()` calls are inflight-unique**\n   *\n   * If you call `fetch()` multiple times with the same key value,\n   * then every call after the first will resolve on the same\n   * promise1,\n   * _even if they have different settings that would otherwise change\n   * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n   * or `ignoreFetchAbort`.\n   *\n   * In most cases, this is not a problem (in fact, only fetching\n   * something once is what you probably want, if you're caching in\n   * the first place). If you are changing the fetch() options\n   * dramatically between runs, there's a good chance that you might\n   * be trying to fit divergent semantics into a single object, and\n   * would be better off with multiple cache instances.\n   *\n   * **1**: Ie, they're not the \"same Promise\", but they resolve at\n   * the same time, because they're both waiting on the same\n   * underlying fetchMethod response.\n   */\n\n  fetch(\n    k: K,\n    fetchOptions: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ?\n      LRUCache.FetchOptionsNoContext\n    : LRUCache.FetchOptionsWithContext,\n  ): Promise\n\n  // this overload not allowed if context is required\n  fetch(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    fetchOptions?: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ?\n      LRUCache.FetchOptionsNoContext\n    : never,\n  ): Promise\n  fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const ths = tracing.hasSubscribers\n    const { status = hasSubscribers() ? {} : undefined } = fetchOptions\n    fetchOptions.status = status\n    if (status && fetchOptions.context) {\n      status.context = fetchOptions.context\n    }\n    const p = this.#fetch(k, fetchOptions)\n    if (status && ths) {\n      status.trace = true\n      tracing.tracePromise(() => p, status).catch(() => {})\n    }\n    return p\n  }\n\n  async #fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const {\n      // get options\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      // set options\n      ttl = this.ttl,\n      noDisposeOnSet = this.noDisposeOnSet,\n      size = 0,\n      sizeCalculation = this.sizeCalculation,\n      noUpdateTTL = this.noUpdateTTL,\n      // fetch exclusive options\n      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n      ignoreFetchAbort = this.ignoreFetchAbort,\n      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n      context,\n      forceRefresh = false,\n      status,\n      signal,\n    } = fetchOptions\n    if (status) {\n      status.op = 'fetch'\n      status.key = k\n      if (forceRefresh) status.forceRefresh = true\n      status.cache = this\n    }\n\n    if (!this.#hasFetchMethod) {\n      if (status) status.fetch = 'get'\n      return this.#get(k, {\n        allowStale,\n        updateAgeOnGet,\n        noDeleteOnStaleGet,\n        status,\n      })\n    }\n\n    const options = {\n      allowStale,\n      updateAgeOnGet,\n      noDeleteOnStaleGet,\n      ttl,\n      noDisposeOnSet,\n      size,\n      sizeCalculation,\n      noUpdateTTL,\n      noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      status,\n      signal,\n    }\n\n    let index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.fetch = 'miss'\n      const p = this.#backgroundFetch(k, index, options, context as FC)\n      return (p.__returned = p)\n    } else {\n      // in cache, maybe already fetching\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        const stale = allowStale && v.__staleWhileFetching !== undefined\n        if (status) {\n          status.fetch = 'inflight'\n          if (stale) status.returnedStale = true\n        }\n        return stale ? v.__staleWhileFetching : (v.__returned = v)\n      }\n\n      // if we force a refresh, that means do NOT serve the cached value,\n      // unless we are already in the process of refreshing the cache.\n      const isStale = this.#isStale(index)\n      if (!forceRefresh && !isStale) {\n        if (status) status.fetch = 'hit'\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        if (status) this.#statusTTL(status, index)\n        return v\n      }\n\n      // ok, it is stale or a forced refresh, and not already fetching.\n      // refresh the cache.\n      const p = this.#backgroundFetch(k, index, options, context as FC)\n      const hasStale = p.__staleWhileFetching !== undefined\n      const staleVal = hasStale && allowStale\n      if (status) {\n        status.fetch = isStale ? 'stale' : 'refresh'\n        if (staleVal && isStale) status.returnedStale = true\n      }\n      return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n    }\n  }\n\n  /**\n   * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n   * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n   * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n   * because `ignoreFetchAbort` was specified (either to the constructor or\n   * in the {@link LRUCache.FetchOptions}). Also, the\n   * {@link LRUCache.OptionsBase.fetchMethod} may return `undefined` or `void`, making\n   * the test even more complicated.\n   *\n   * Because inferring the cases where `undefined` might be returned are so\n   * cumbersome, but testing for `undefined` can also be annoying, this method\n   * can be used, which will reject if `this.fetch()` resolves to undefined.\n   */\n  forceFetch(\n    k: K,\n    fetchOptions: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ?\n      LRUCache.FetchOptionsNoContext\n    : LRUCache.FetchOptionsWithContext,\n  ): Promise\n  // this overload not allowed if context is required\n  forceFetch(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    fetchOptions?: unknown extends FC ? LRUCache.FetchOptions\n    : FC extends undefined | void ?\n      LRUCache.FetchOptionsNoContext\n    : never,\n  ): Promise\n  forceFetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ): Promise {\n    const ths = tracing.hasSubscribers\n    const { status = hasSubscribers() ? {} : undefined } = fetchOptions\n    fetchOptions.status = status\n    if (status && fetchOptions.context) {\n      status.context = fetchOptions.context\n    }\n    const p = this.#forceFetch(k, fetchOptions)\n    if (status && ths) {\n      status.trace = true\n      tracing.tracePromise(() => p, status).catch(() => {})\n    }\n    return p\n  }\n\n  async #forceFetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {},\n  ) {\n    const v = await this.#fetch(k, fetchOptions)\n    if (v === undefined) throw new Error('fetch() returned undefined')\n    return v\n  }\n\n  /**\n   * If the key is found in the cache, then this is equivalent to\n   * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n   * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n   * _must_ provide a `context` option. If set to `undefined` or `void`, then\n   * calls to memo _must not_ provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that might be\n   * relevant in the course of fetching the data. It is only relevant for the\n   * course of a single `memo()` operation, and discarded afterwards.\n   */\n  memo(\n    k: K,\n    memoOptions: unknown extends FC ? LRUCache.MemoOptions\n    : FC extends undefined | void ? LRUCache.MemoOptionsNoContext\n    : LRUCache.MemoOptionsWithContext,\n  ): V\n  // this overload not allowed if context is required\n  memo(\n    k: unknown extends FC ? K\n    : FC extends undefined | void ? K\n    : never,\n    memoOptions?: unknown extends FC ? LRUCache.MemoOptions\n    : FC extends undefined | void ? LRUCache.MemoOptionsNoContext\n    : never,\n  ): V\n  memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n    const { status = metrics.hasSubscribers ? {} : undefined } =\n      memoOptions\n    memoOptions.status = status\n    if (status) {\n      status.op = 'memo'\n      status.key = k\n      if (memoOptions.context) {\n        status.context = memoOptions.context\n      }\n      status.cache = this\n    }\n    const result = this.#memo(k, memoOptions)\n    if (status) status.value = result\n    if (metrics.hasSubscribers) metrics.publish(status)\n    return result\n  }\n  #memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n    const memoMethod = this.#memoMethod\n    if (!memoMethod) {\n      throw new Error('no memoMethod provided to constructor')\n    }\n    const { context, status, forceRefresh, ...options } = memoOptions\n    if (status && forceRefresh) status.forceRefresh = true\n    const v = this.#get(k, options)\n    const refresh = forceRefresh || v === undefined\n    if (status) {\n      status.memo = refresh ? 'miss' : 'hit'\n      if (!refresh) status.value = v\n    }\n    if (!refresh) return v\n    const vv = memoMethod(k, v, {\n      options,\n      context,\n    } as LRUCache.MemoizerOptions)\n    if (status) status.value = vv\n    this.#set(k, vv, options)\n    return vv\n  }\n\n  /**\n   * Return a value from the cache. Will update the recency of the cache\n   * entry found.\n   *\n   * If the key is not found, get() will return `undefined`.\n   */\n  get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const { status = metrics.hasSubscribers ? {} : undefined } = getOptions\n    getOptions.status = status\n    if (status) {\n      status.op = 'get'\n      status.key = k\n      status.cache = this\n    }\n    const result = this.#get(k, getOptions)\n    if (status) {\n      if (result !== undefined) status.value = result\n      if (metrics.hasSubscribers) metrics.publish(status)\n    }\n    return result\n  }\n\n  #get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const {\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      status,\n    } = getOptions\n    const index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.get = 'miss'\n      return undefined\n    }\n    const value = this.#valList[index]\n    const fetching = this.#isBackgroundFetch(value)\n    if (status) this.#statusTTL(status, index)\n    if (this.#isStale(index)) {\n      // delete only if not an in-flight background fetch\n      if (!fetching) {\n        if (!noDeleteOnStaleGet) {\n          this.#delete(k, 'expire')\n        }\n        if (status) status.get = 'stale'\n        if (allowStale) {\n          if (status) status.returnedStale = true\n          return value\n        }\n        return undefined\n      }\n      if (status) status.get = 'stale-fetching'\n      if (allowStale && value.__staleWhileFetching !== undefined) {\n        if (status) status.returnedStale = true\n        return value.__staleWhileFetching\n      }\n      return undefined\n    }\n    // not stale\n    if (status) status.get = fetching ? 'fetching' : 'hit'\n    // if we're currently fetching it, we don't actually have it yet\n    // it's not stale, which means this isn't a staleWhileRefetching.\n    // If it's not stale, and fetching, AND has a __staleWhileFetching\n    // value, then that means the user fetched with {forceRefresh:true},\n    // so it's safe to return that value.\n    this.#moveToTail(index)\n    if (updateAgeOnGet) {\n      this.#updateItemAge(index)\n    }\n    return fetching ? value.__staleWhileFetching : value\n  }\n\n  #connect(p: Index, n: Index) {\n    this.#prev[n] = p\n    this.#next[p] = n\n  }\n\n  #moveToTail(index: Index): void {\n    // if tail already, nothing to do\n    // if head, move head to next[index]\n    // else\n    //   move next[prev[index]] to next[index] (head has no prev)\n    //   move prev[next[index]] to prev[index]\n    // prev[index] = tail\n    // next[tail] = index\n    // tail = index\n    if (index !== this.#tail) {\n      if (index === this.#head) {\n        this.#head = this.#next[index] as Index\n      } else {\n        this.#connect(\n          this.#prev[index] as Index,\n          this.#next[index] as Index,\n        )\n      }\n      this.#connect(this.#tail, index)\n      this.#tail = index\n    }\n  }\n\n  /**\n   * Deletes a key out of the cache.\n   *\n   * Returns true if the key was deleted, false otherwise.\n   */\n  delete(k: K) {\n    return this.#delete(k, 'delete')\n  }\n\n  #delete(k: K, reason: LRUCache.DisposeReason) {\n    if (metrics.hasSubscribers) {\n      metrics.publish({\n        op: 'delete',\n        delete: reason,\n        key: k,\n        cache: this,\n      })\n    }\n    let deleted = false\n    if (this.#size !== 0) {\n      const index = this.#keyMap.get(k)\n      if (index !== undefined) {\n        if (this.#autopurgeTimers?.[index]) {\n          clearTimeout(this.#autopurgeTimers[index])\n          this.#autopurgeTimers[index] = undefined\n        }\n        deleted = true\n        if (this.#size === 1) {\n          this.#clear(reason)\n        } else {\n          this.#removeItemSize(index)\n          const v = this.#valList[index]\n          if (this.#isBackgroundFetch(v)) {\n            v.__abortController.abort(new Error('deleted'))\n          } else if (this.#hasDispose || this.#hasDisposeAfter) {\n            if (this.#hasDispose) {\n              this.#dispose?.(v as V, k, reason)\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([v as V, k, reason])\n            }\n          }\n          this.#keyMap.delete(k)\n          this.#keyList[index] = undefined\n          this.#valList[index] = undefined\n          if (index === this.#tail) {\n            this.#tail = this.#prev[index] as Index\n          } else if (index === this.#head) {\n            this.#head = this.#next[index] as Index\n          } else {\n            const pi = this.#prev[index] as number\n            this.#next[pi] = this.#next[index] as number\n            const ni = this.#next[index] as number\n            this.#prev[ni] = this.#prev[index] as number\n          }\n          this.#size--\n          this.#free.push(index)\n        }\n      }\n    }\n    if (this.#hasDisposeAfter && this.#disposed?.length) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Clear the cache entirely, throwing away all values.\n   */\n  clear() {\n    return this.#clear('delete')\n  }\n  #clear(reason: LRUCache.DisposeReason) {\n    for (const index of this.#rindexes({ allowStale: true })) {\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        v.__abortController.abort(new Error('deleted'))\n      } else {\n        const k = this.#keyList[index]\n        if (this.#hasDispose) {\n          this.#dispose?.(v as V, k as K, reason)\n        }\n        if (this.#hasDisposeAfter) {\n          this.#disposed?.push([v as V, k as K, reason])\n        }\n      }\n    }\n\n    this.#keyMap.clear()\n    void this.#valList.fill(undefined)\n    this.#keyList.fill(undefined)\n    if (this.#ttls && this.#starts) {\n      this.#ttls.fill(0)\n      this.#starts.fill(0)\n      for (const t of this.#autopurgeTimers ?? []) {\n        if (t !== undefined) clearTimeout(t)\n      }\n      this.#autopurgeTimers?.fill(undefined)\n    }\n    if (this.#sizes) {\n      this.#sizes.fill(0)\n    }\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free.length = 0\n    this.#calculatedSize = 0\n    this.#size = 0\n    if (this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n  }\n}\n", "import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\, and //?/UNC/host/share/ or\n// //host/share into \\\\host\\share\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncLongRegexp = /^\\\\\\\\\\?\\\\UNC\\\\([^\\\\]+\\\\[^\\\\]+)\\\\?$/i\nconst uncShareRegexp = /^\\\\\\\\[^\\\\?]+\\\\[^\\\\]+$/\nconst uncToDrive = (rootPath: string): string =>\n  rootPath\n    .replace(/\\//g, '\\\\')\n    .replace(uncDriveRegexp, '$1\\\\')\n    .replace(uncLongRegexp, '\\\\\\\\$1\\\\')\n    .replace(uncShareRegexp, '$&\\\\')\n\n// path.win32.parse() only finds the //?/UNC/ of a long UNC root\nconst longUncRoot =\n  /^[\\\\/]{2}\\?[\\\\/]unc[\\\\/][^\\\\/]+[\\\\/][^\\\\/]+(?:[\\\\/]|$)/i\n\n// //?/c:/x is the same path as c:/x\nconst longDrivePrefix = /^[\\\\/]{2}\\?[\\\\/](?=[a-z]:)/i\n// //?/UNC/host/share/x is the same path as //host/share/x. This\n// matches up to the / after UNC, which with a \\ in front of it is\n// the // in front of the host.\nconst longUncPrefix = /^[\\\\/]{2}\\?[\\\\/]unc(?=[\\\\/][^\\\\/]+[\\\\/][^\\\\/])/i\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new LRUCache({ max: 2 ** 12 })\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new LRUCache({ max: 2 ** 12 })\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /* c8 ignore start */\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   *\n   * @deprecated\n   */\n  get path(): string {\n    return this.parentPath\n  }\n  /* c8 ignore stop */\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * The file system methods that this Path uses, for a new root on\n   * another drive or UNC share.\n   *\n   * @internal\n   */\n  get fs(): FSOption {\n    return this.#fs\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return longUncRoot.exec(path)?.[0] ?? win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    // a root with no drive or UNC host is the root of this path\n    if (rootPath === this.root.name || /^[\\\\/]$/.test(rootPath)) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(rootPath, {\n      nocase: this.nocase,\n      fs: this.fs,\n    }).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    return uncToDrive(rootPath.toUpperCase()) === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    // use the same root as resolve() does for these paths\n    if (typeof cwd === 'string' && !cwd.startsWith('file://')) {\n      cwd = cwd.replace(longDrivePrefix, '').replace(longUncPrefix, '\\\\')\n    }\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n", "const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n  s: any\n): s is Minipass.Readable | Minipass.Writable =>\n  !!s &&\n  typeof s === 'object' &&\n  (s instanceof Minipass ||\n    s instanceof Stream ||\n    isReadable(s) ||\n    isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Readable).pipe === 'function' &&\n  // node core Writable streams have a pipe() method, but it throws\n  (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Writable).write === 'function' &&\n  typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n  ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n  b instanceof ArrayBuffer ||\n  (!!b &&\n    typeof b === 'object' &&\n    b.constructor &&\n    b.constructor.name === 'ArrayBuffer' &&\n    b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n  !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n  /**\n   * end the destination stream when the source stream ends\n   */\n  end?: boolean\n  /**\n   * proxy errors from the source stream to the destination stream\n   */\n  proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n  src: Minipass\n  dest: Minipass\n  opts: PipeOptions\n  ondrain: () => any\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    this.src = src\n    this.dest = dest as Minipass\n    this.opts = opts\n    this.ondrain = () => src[RESUME]()\n    this.dest.on('drain', this.ondrain)\n  }\n  unpipe() {\n    this.dest.removeListener('drain', this.ondrain)\n  }\n  // only here for the prototype\n  /* c8 ignore start */\n  proxyErrors(_er: any) {}\n  /* c8 ignore stop */\n  end() {\n    this.unpipe()\n    if (this.opts.end) this.dest.end()\n  }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n  unpipe() {\n    this.src.removeListener('error', this.proxyErrors)\n    super.unpipe()\n  }\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    super(src, dest, opts)\n    this.proxyErrors = (er: Error) => this.dest.emit('error', er)\n    src.on('error', this.proxyErrors)\n  }\n}\n\nexport namespace Minipass {\n  /**\n   * Encoding used to create a stream that outputs strings rather than\n   * Buffer objects.\n   */\n  export type Encoding = BufferEncoding | 'buffer' | null\n\n  /**\n   * Any stream that Minipass can pipe into\n   */\n  export type Writable =\n    | Minipass\n    | NodeJS.WriteStream\n    | (NodeJS.WriteStream & { fd: number })\n    | (EventEmitter & {\n        end(): any\n        write(chunk: any, ...args: any[]): any\n      })\n\n  /**\n   * Any stream that can be read from\n   */\n  export type Readable =\n    | Minipass\n    | NodeJS.ReadStream\n    | (NodeJS.ReadStream & { fd: number })\n    | (EventEmitter & {\n        pause(): any\n        resume(): any\n        pipe(...destArgs: any[]): any\n      })\n\n  /**\n   * Utility type that can be iterated sync or async\n   */\n  export type DualIterable = Iterable & AsyncIterable\n\n  type EventArguments = Record\n\n  /**\n   * The listing of events that a Minipass class can emit.\n   * Extend this when extending the Minipass class, and pass as\n   * the third template argument.  The key is the name of the event,\n   * and the value is the argument list.\n   *\n   * Any undeclared events will still be allowed, but the handler will get\n   * arguments as `unknown[]`.\n   */\n  export interface Events\n    extends EventArguments {\n    readable: []\n    data: [chunk: RType]\n    error: [er: unknown]\n    abort: [reason: unknown]\n    drain: []\n    resume: []\n    end: []\n    finish: []\n    prefinish: []\n    close: []\n    [DESTROYED]: [er?: unknown]\n    [ERROR]: [er: unknown]\n  }\n\n  /**\n   * String or buffer-like data that can be joined and sliced\n   */\n  export type ContiguousData =\n    | Buffer\n    | ArrayBufferLike\n    | ArrayBufferView\n    | string\n  export type BufferOrString = Buffer | string\n\n  /**\n   * Options passed to the Minipass constructor.\n   */\n  export type SharedOptions = {\n    /**\n     * Defer all data emission and other events until the end of the\n     * current tick, similar to Node core streams\n     */\n    async?: boolean\n    /**\n     * A signal which will abort the stream\n     */\n    signal?: AbortSignal\n    /**\n     * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n     * emit Buffer objects rather than strings.\n     *\n     * Conflicts with `objectMode`\n     */\n    encoding?: BufferEncoding | null | 'buffer'\n    /**\n     * Output data exactly as it was written, supporting non-buffer/string\n     * data (such as arbitrary objects, falsey values, etc.)\n     *\n     * Conflicts with `encoding`\n     */\n    objectMode?: boolean\n  }\n\n  /**\n   * Options for a string encoded output\n   */\n  export type EncodingOptions = SharedOptions & {\n    encoding: BufferEncoding\n    objectMode?: false\n  }\n\n  /**\n   * Options for contiguous data buffer output\n   */\n  export type BufferOptions = SharedOptions & {\n    encoding?: null | 'buffer'\n    objectMode?: false\n  }\n\n  /**\n   * Options for objectMode arbitrary output\n   */\n  export type ObjectModeOptions = SharedOptions & {\n    objectMode: true\n    encoding?: null\n  }\n\n  /**\n   * Utility type to determine allowed options based on read type\n   */\n  export type Options =\n    | ObjectModeOptions\n    | (T extends string\n        ? EncodingOptions\n        : T extends Buffer\n        ? BufferOptions\n        : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n  !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n    RType extends unknown = Buffer,\n    WType extends unknown = RType extends Minipass.BufferOrString\n      ? Minipass.ContiguousData\n      : RType,\n    Events extends Minipass.Events = Minipass.Events\n  >\n  extends EventEmitter\n  implements Minipass.DualIterable\n{\n  [FLOWING]: boolean = false;\n  [PAUSED]: boolean = false;\n  [PIPES]: Pipe[] = [];\n  [BUFFER]: RType[] = [];\n  [OBJECTMODE]: boolean;\n  [ENCODING]: BufferEncoding | null;\n  [ASYNC]: boolean;\n  [DECODER]: SD | null;\n  [EOF]: boolean = false;\n  [EMITTED_END]: boolean = false;\n  [EMITTING_END]: boolean = false;\n  [CLOSED]: boolean = false;\n  [EMITTED_ERROR]: unknown = null;\n  [BUFFERLENGTH]: number = 0;\n  [DESTROYED]: boolean = false;\n  [SIGNAL]?: AbortSignal;\n  [ABORTED]: boolean = false;\n  [DATALISTENERS]: number = 0;\n  [DISCARDED]: boolean = false\n\n  /**\n   * true if the stream can be written\n   */\n  writable: boolean = true\n  /**\n   * true if the stream can be read\n   */\n  readable: boolean = true\n\n  /**\n   * If `RType` is Buffer, then options do not need to be provided.\n   * Otherwise, an options object must be provided to specify either\n   * {@link Minipass.SharedOptions.objectMode} or\n   * {@link Minipass.SharedOptions.encoding}, as appropriate.\n   */\n  constructor(\n    ...args:\n      | [Minipass.ObjectModeOptions]\n      | (RType extends Buffer\n          ? [] | [Minipass.Options]\n          : [Minipass.Options])\n  ) {\n    const options: Minipass.Options = (args[0] ||\n      {}) as Minipass.Options\n    super()\n    if (options.objectMode && typeof options.encoding === 'string') {\n      throw new TypeError(\n        'Encoding and objectMode may not be used together'\n      )\n    }\n    if (isObjectModeOptions(options)) {\n      this[OBJECTMODE] = true\n      this[ENCODING] = null\n    } else if (isEncodingOptions(options)) {\n      this[ENCODING] = options.encoding\n      this[OBJECTMODE] = false\n    } else {\n      this[OBJECTMODE] = false\n      this[ENCODING] = null\n    }\n    this[ASYNC] = !!options.async\n    this[DECODER] = this[ENCODING]\n      ? (new StringDecoder(this[ENCODING]) as SD)\n      : null\n\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposeBuffer === true) {\n      Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n    }\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposePipes === true) {\n      Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n    }\n\n    const { signal } = options\n    if (signal) {\n      this[SIGNAL] = signal\n      if (signal.aborted) {\n        this[ABORT]()\n      } else {\n        signal.addEventListener('abort', () => this[ABORT]())\n      }\n    }\n  }\n\n  /**\n   * The amount of data stored in the buffer waiting to be read.\n   *\n   * For Buffer strings, this will be the total byte length.\n   * For string encoding streams, this will be the string character length,\n   * according to JavaScript's `string.length` logic.\n   * For objectMode streams, this is a count of the items waiting to be\n   * emitted.\n   */\n  get bufferLength() {\n    return this[BUFFERLENGTH]\n  }\n\n  /**\n   * The `BufferEncoding` currently in use, or `null`\n   */\n  get encoding() {\n    return this[ENCODING]\n  }\n\n  /**\n   * @deprecated - This is a read only property\n   */\n  set encoding(_enc) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * @deprecated - Encoding may only be set at instantiation time\n   */\n  setEncoding(_enc: Minipass.Encoding) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * True if this is an objectMode stream\n   */\n  get objectMode() {\n    return this[OBJECTMODE]\n  }\n\n  /**\n   * @deprecated - This is a read-only property\n   */\n  set objectMode(_om) {\n    throw new Error('objectMode must be set at instantiation time')\n  }\n\n  /**\n   * true if this is an async stream\n   */\n  get ['async'](): boolean {\n    return this[ASYNC]\n  }\n  /**\n   * Set to true to make this stream async.\n   *\n   * Once set, it cannot be unset, as this would potentially cause incorrect\n   * behavior.  Ie, a sync stream can be made async, but an async stream\n   * cannot be safely made sync.\n   */\n  set ['async'](a: boolean) {\n    this[ASYNC] = this[ASYNC] || !!a\n  }\n\n  // drop everything and get out of the flow completely\n  [ABORT]() {\n    this[ABORTED] = true\n    this.emit('abort', this[SIGNAL]?.reason)\n    this.destroy(this[SIGNAL]?.reason)\n  }\n\n  /**\n   * True if the stream has been aborted.\n   */\n  get aborted() {\n    return this[ABORTED]\n  }\n  /**\n   * No-op setter. Stream aborted status is set via the AbortSignal provided\n   * in the constructor options.\n   */\n  set aborted(_) {}\n\n  /**\n   * Write data into the stream\n   *\n   * If the chunk written is a string, and encoding is not specified, then\n   * `utf8` will be assumed. If the stream encoding matches the encoding of\n   * a written string, and the state of the string decoder allows it, then\n   * the string will be passed through to either the output or the internal\n   * buffer without any processing. Otherwise, it will be turned into a\n   * Buffer object for processing into the desired encoding.\n   *\n   * If provided, `cb` function is called immediately before return for\n   * sync streams, or on next tick for async streams, because for this\n   * base class, a chunk is considered \"processed\" once it is accepted\n   * and either emitted or buffered. That is, the callback does not indicate\n   * that the chunk has been eventually emitted, though of course child\n   * classes can override this function to do whatever processing is required\n   * and call `super.write(...)` only once processing is completed.\n   */\n  write(chunk: WType, cb?: () => void): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding,\n    cb?: () => void\n  ): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): boolean {\n    if (this[ABORTED]) return false\n    if (this[EOF]) throw new Error('write after end')\n\n    if (this[DESTROYED]) {\n      this.emit(\n        'error',\n        Object.assign(\n          new Error('Cannot call write after a stream was destroyed'),\n          { code: 'ERR_STREAM_DESTROYED' }\n        )\n      )\n      return true\n    }\n\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n\n    if (!encoding) encoding = 'utf8'\n\n    const fn = this[ASYNC] ? defer : nodefer\n\n    // convert array buffers and typed array views into buffers\n    // at some point in the future, we may want to do the opposite!\n    // leave strings and buffers as-is\n    // anything is only allowed if in object mode, so throw\n    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n      if (isArrayBufferView(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(\n          chunk.buffer,\n          chunk.byteOffset,\n          chunk.byteLength\n        )\n      } else if (isArrayBufferLike(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(chunk)\n      } else if (typeof chunk !== 'string') {\n        throw new Error(\n          'Non-contiguous data written to non-objectMode stream'\n        )\n      }\n    }\n\n    // handle object mode up front, since it's simpler\n    // this yields better performance, fewer checks later.\n    if (this[OBJECTMODE]) {\n      // maybe impossible?\n      /* c8 ignore start */\n      if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n      /* c8 ignore stop */\n\n      if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n      else this[BUFFERPUSH](chunk as unknown as RType)\n\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n      if (cb) fn(cb)\n\n      return this[FLOWING]\n    }\n\n    // at this point the chunk is a buffer or string\n    // don't buffer it up or send it to the decoder\n    if (!(chunk as Minipass.BufferOrString).length) {\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n      if (cb) fn(cb)\n      return this[FLOWING]\n    }\n\n    // fast-path writing strings of same encoding to a stream with\n    // an empty buffer, skipping the buffer/decoder dance\n    if (\n      typeof chunk === 'string' &&\n      // unless it is a string already ready for us to use\n      !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n    ) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = Buffer.from(chunk, encoding)\n    }\n\n    if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = this[DECODER].write(chunk)\n    }\n\n    // Note: flushing CAN potentially switch us into not-flowing mode\n    if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n    if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n    else this[BUFFERPUSH](chunk as unknown as RType)\n\n    if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n    if (cb) fn(cb)\n\n    return this[FLOWING]\n  }\n\n  /**\n   * Low-level explicit read method.\n   *\n   * In objectMode, the argument is ignored, and one item is returned if\n   * available.\n   *\n   * `n` is the number of bytes (or in the case of encoding streams,\n   * characters) to consume. If `n` is not provided, then the entire buffer\n   * is returned, or `null` is returned if no data is available.\n   *\n   * If `n` is greater that the amount of data in the internal buffer,\n   * then `null` is returned.\n   */\n  read(n?: number | null): RType | null {\n    if (this[DESTROYED]) return null\n    this[DISCARDED] = false\n\n    if (\n      this[BUFFERLENGTH] === 0 ||\n      n === 0 ||\n      (n && n > this[BUFFERLENGTH])\n    ) {\n      this[MAYBE_EMIT_END]()\n      return null\n    }\n\n    if (this[OBJECTMODE]) n = null\n\n    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n      // not object mode, so if we have an encoding, then RType is string\n      // otherwise, must be Buffer\n      this[BUFFER] = [\n        (this[ENCODING]\n          ? this[BUFFER].join('')\n          : Buffer.concat(\n              this[BUFFER] as Buffer[],\n              this[BUFFERLENGTH]\n            )) as RType,\n      ]\n    }\n\n    const ret = this[READ](n || null, this[BUFFER][0] as RType)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [READ](n: number | null, chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n    else {\n      const c = chunk as Minipass.BufferOrString\n      if (n === c.length || n === null) this[BUFFERSHIFT]()\n      else if (typeof c === 'string') {\n        this[BUFFER][0] = c.slice(n) as RType\n        chunk = c.slice(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      } else {\n        this[BUFFER][0] = c.subarray(n) as RType\n        chunk = c.subarray(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      }\n    }\n\n    this.emit('data', chunk)\n\n    if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n    return chunk\n  }\n\n  /**\n   * End the stream, optionally providing a final write.\n   *\n   * See {@link Minipass#write} for argument descriptions\n   */\n  end(cb?: () => void): this\n  end(chunk: WType, cb?: () => void): this\n  end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n  end(\n    chunk?: WType | (() => void),\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): this {\n    if (typeof chunk === 'function') {\n      cb = chunk as () => void\n      chunk = undefined\n    }\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n    if (chunk !== undefined) this.write(chunk, encoding)\n    if (cb) this.once('end', cb)\n    this[EOF] = true\n    this.writable = false\n\n    // if we haven't written anything, then go ahead and emit,\n    // even if we're not reading.\n    // we'll re-emit if a new 'end' listener is added anyway.\n    // This makes MP more suitable to write-only use cases.\n    if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n    return this\n  }\n\n  // don't let the internal resume be overwritten\n  [RESUME]() {\n    if (this[DESTROYED]) return\n\n    if (!this[DATALISTENERS] && !this[PIPES].length) {\n      this[DISCARDED] = true\n    }\n    this[PAUSED] = false\n    this[FLOWING] = true\n    this.emit('resume')\n    if (this[BUFFER].length) this[FLUSH]()\n    else if (this[EOF]) this[MAYBE_EMIT_END]()\n    else this.emit('drain')\n  }\n\n  /**\n   * Resume the stream if it is currently in a paused state\n   *\n   * If called when there are no pipe destinations or `data` event listeners,\n   * this will place the stream in a \"discarded\" state, where all data will\n   * be thrown away. The discarded state is removed if a pipe destination or\n   * data handler is added, if pause() is called, or if any synchronous or\n   * asynchronous iteration is started.\n   */\n  resume() {\n    return this[RESUME]()\n  }\n\n  /**\n   * Pause the stream\n   */\n  pause() {\n    this[FLOWING] = false\n    this[PAUSED] = true\n    this[DISCARDED] = false\n  }\n\n  /**\n   * true if the stream has been forcibly destroyed\n   */\n  get destroyed() {\n    return this[DESTROYED]\n  }\n\n  /**\n   * true if the stream is currently in a flowing state, meaning that\n   * any writes will be immediately emitted.\n   */\n  get flowing() {\n    return this[FLOWING]\n  }\n\n  /**\n   * true if the stream is currently in a paused state\n   */\n  get paused() {\n    return this[PAUSED]\n  }\n\n  [BUFFERPUSH](chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n    else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n    this[BUFFER].push(chunk)\n  }\n\n  [BUFFERSHIFT](): RType {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n    else\n      this[BUFFERLENGTH] -= (\n        this[BUFFER][0] as Minipass.BufferOrString\n      ).length\n    return this[BUFFER].shift() as RType\n  }\n\n  [FLUSH](noDrain: boolean = false) {\n    do {} while (\n      this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n      this[BUFFER].length\n    )\n\n    if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n  }\n\n  [FLUSHCHUNK](chunk: RType) {\n    this.emit('data', chunk)\n    return this[FLOWING]\n  }\n\n  /**\n   * Pipe all data emitted by this stream into the destination provided.\n   *\n   * Triggers the flow of data.\n   */\n  pipe(dest: W, opts?: PipeOptions): W {\n    if (this[DESTROYED]) return dest\n    this[DISCARDED] = false\n\n    const ended = this[EMITTED_END]\n    opts = opts || {}\n    if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n    else opts.end = opts.end !== false\n    opts.proxyErrors = !!opts.proxyErrors\n\n    // piping an ended stream ends immediately\n    if (ended) {\n      if (opts.end) dest.end()\n    } else {\n      // \"as\" here just ignores the WType, which pipes don't care about,\n      // since they're only consuming from us, and writing to the dest\n      this[PIPES].push(\n        !opts.proxyErrors\n          ? new Pipe(this as Minipass, dest, opts)\n          : new PipeProxyErrors(this as Minipass, dest, opts)\n      )\n      if (this[ASYNC]) defer(() => this[RESUME]())\n      else this[RESUME]()\n    }\n\n    return dest\n  }\n\n  /**\n   * Fully unhook a piped destination stream.\n   *\n   * If the destination stream was the only consumer of this stream (ie,\n   * there are no other piped destinations or `'data'` event listeners)\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  unpipe(dest: W) {\n    const p = this[PIPES].find(p => p.dest === dest)\n    if (p) {\n      if (this[PIPES].length === 1) {\n        if (this[FLOWING] && this[DATALISTENERS] === 0) {\n          this[FLOWING] = false\n        }\n        this[PIPES] = []\n      } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n      p.unpipe()\n    }\n  }\n\n  /**\n   * Alias for {@link Minipass#on}\n   */\n  addListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    return this.on(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.on`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * - Adding a 'data' event handler will trigger the flow of data\n   *\n   * - Adding a 'readable' event handler when there is data waiting to be read\n   *   will cause 'readable' to be emitted immediately.\n   *\n   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n   *   already passed will cause the event to be emitted immediately and all\n   *   handlers removed.\n   *\n   * - Adding an 'error' event handler after an error has been emitted will\n   *   cause the event to be re-emitted immediately with the error previously\n   *   raised.\n   */\n  on(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    const ret = super.on(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    if (ev === 'data') {\n      this[DISCARDED] = false\n      this[DATALISTENERS]++\n      if (!this[PIPES].length && !this[FLOWING]) {\n        this[RESUME]()\n      }\n    } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n      super.emit('readable')\n    } else if (isEndish(ev) && this[EMITTED_END]) {\n      super.emit(ev)\n      this.removeAllListeners(ev)\n    } else if (ev === 'error' && this[EMITTED_ERROR]) {\n      const h = handler as (...a: Events['error']) => any\n      if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n      else h.call(this, this[EMITTED_ERROR])\n    }\n    return ret\n  }\n\n  /**\n   * Alias for {@link Minipass#off}\n   */\n  removeListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    return this.off(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.off`\n   *\n   * If a 'data' event handler is removed, and it was the last consumer\n   * (ie, there are no pipe destinations or other 'data' event listeners),\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  off(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    const ret = super.off(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    // if we previously had listeners, and now we don't, and we don't\n    // have any pipes, then stop the flow, unless it's been explicitly\n    // put in a discarded flowing state via stream.resume().\n    if (ev === 'data') {\n      this[DATALISTENERS] = this.listeners('data').length\n      if (\n        this[DATALISTENERS] === 0 &&\n        !this[DISCARDED] &&\n        !this[PIPES].length\n      ) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.removeAllListeners`\n   *\n   * If all 'data' event handlers are removed, and they were the last consumer\n   * (ie, there are no pipe destinations), then the flow of data will stop\n   * until there is another consumer or {@link Minipass#resume} is explicitly\n   * called.\n   */\n  removeAllListeners(ev?: Event) {\n    const ret = super.removeAllListeners(ev as string | symbol | undefined)\n    if (ev === 'data' || ev === undefined) {\n      this[DATALISTENERS] = 0\n      if (!this[DISCARDED] && !this[PIPES].length) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * true if the 'end' event has been emitted\n   */\n  get emittedEnd() {\n    return this[EMITTED_END]\n  }\n\n  [MAYBE_EMIT_END]() {\n    if (\n      !this[EMITTING_END] &&\n      !this[EMITTED_END] &&\n      !this[DESTROYED] &&\n      this[BUFFER].length === 0 &&\n      this[EOF]\n    ) {\n      this[EMITTING_END] = true\n      this.emit('end')\n      this.emit('prefinish')\n      this.emit('finish')\n      if (this[CLOSED]) this.emit('close')\n      this[EMITTING_END] = false\n    }\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.emit`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * If the stream has been destroyed, and the event is something other\n   * than 'close' or 'error', then `false` is returned and no handlers\n   * are called.\n   *\n   * If the event is 'end', and has already been emitted, then the event\n   * is ignored. If the stream is in a paused or non-flowing state, then\n   * the event will be deferred until data flow resumes. If the stream is\n   * async, then handlers will be called on the next tick rather than\n   * immediately.\n   *\n   * If the event is 'close', and 'end' has not yet been emitted, then\n   * the event will be deferred until after 'end' is emitted.\n   *\n   * If the event is 'error', and an AbortSignal was provided for the stream,\n   * and there are no listeners, then the event is ignored, matching the\n   * behavior of node core streams in the presense of an AbortSignal.\n   *\n   * If the event is 'finish' or 'prefinish', then all listeners will be\n   * removed after emitting the event, to prevent double-firing.\n   */\n  emit(\n    ev: Event,\n    ...args: Events[Event]\n  ): boolean {\n    const data = args[0]\n    // error and close are only events allowed after calling destroy()\n    if (\n      ev !== 'error' &&\n      ev !== 'close' &&\n      ev !== DESTROYED &&\n      this[DESTROYED]\n    ) {\n      return false\n    } else if (ev === 'data') {\n      return !this[OBJECTMODE] && !data\n        ? false\n        : this[ASYNC]\n        ? (defer(() => this[EMITDATA](data as RType)), true)\n        : this[EMITDATA](data as RType)\n    } else if (ev === 'end') {\n      return this[EMITEND]()\n    } else if (ev === 'close') {\n      this[CLOSED] = true\n      // don't emit close before 'end' and 'finish'\n      if (!this[EMITTED_END] && !this[DESTROYED]) return false\n      const ret = super.emit('close')\n      this.removeAllListeners('close')\n      return ret\n    } else if (ev === 'error') {\n      this[EMITTED_ERROR] = data\n      super.emit(ERROR, data)\n      const ret =\n        !this[SIGNAL] || this.listeners('error').length\n          ? super.emit('error', data)\n          : false\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'resume') {\n      const ret = super.emit('resume')\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'finish' || ev === 'prefinish') {\n      const ret = super.emit(ev)\n      this.removeAllListeners(ev)\n      return ret\n    }\n\n    // Some other unknown event\n    const ret = super.emit(ev as string, ...args)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITDATA](data: RType) {\n    for (const p of this[PIPES]) {\n      if (p.dest.write(data as RType) === false) this.pause()\n    }\n    const ret = this[DISCARDED] ? false : super.emit('data', data)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITEND]() {\n    if (this[EMITTED_END]) return false\n\n    this[EMITTED_END] = true\n    this.readable = false\n    return this[ASYNC]\n      ? (defer(() => this[EMITEND2]()), true)\n      : this[EMITEND2]()\n  }\n\n  [EMITEND2]() {\n    if (this[DECODER]) {\n      const data = this[DECODER].end()\n      if (data) {\n        for (const p of this[PIPES]) {\n          p.dest.write(data as RType)\n        }\n        if (!this[DISCARDED]) super.emit('data', data)\n      }\n    }\n\n    for (const p of this[PIPES]) {\n      p.end()\n    }\n    const ret = super.emit('end')\n    this.removeAllListeners('end')\n    return ret\n  }\n\n  /**\n   * Return a Promise that resolves to an array of all emitted data once\n   * the stream ends.\n   */\n  async collect(): Promise {\n    const buf: RType[] & { dataLength: number } = Object.assign([], {\n      dataLength: 0,\n    })\n    if (!this[OBJECTMODE]) buf.dataLength = 0\n    // set the promise first, in case an error is raised\n    // by triggering the flow here.\n    const p = this.promise()\n    this.on('data', c => {\n      buf.push(c)\n      if (!this[OBJECTMODE])\n        buf.dataLength += (c as Minipass.BufferOrString).length\n    })\n    await p\n    return buf\n  }\n\n  /**\n   * Return a Promise that resolves to the concatenation of all emitted data\n   * once the stream ends.\n   *\n   * Not allowed on objectMode streams.\n   */\n  async concat(): Promise {\n    if (this[OBJECTMODE]) {\n      throw new Error('cannot concat in objectMode')\n    }\n    const buf = await this.collect()\n    return (\n      this[ENCODING]\n        ? buf.join('')\n        : Buffer.concat(buf as Buffer[], buf.dataLength)\n    ) as RType\n  }\n\n  /**\n   * Return a void Promise that resolves once the stream ends.\n   */\n  async promise(): Promise {\n    return new Promise((resolve, reject) => {\n      this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n      this.on('error', er => reject(er))\n      this.on('end', () => resolve())\n    })\n  }\n\n  /**\n   * Asynchronous `for await of` iteration.\n   *\n   * This will continue emitting all chunks until the stream terminates.\n   */\n  [Symbol.asyncIterator](): AsyncGenerator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = async (): Promise> => {\n      this.pause()\n      stopped = true\n      return { value: undefined, done: true }\n    }\n    const next = (): Promise> => {\n      if (stopped) return stop()\n      const res = this.read()\n      if (res !== null) return Promise.resolve({ done: false, value: res })\n\n      if (this[EOF]) return stop()\n\n      let resolve!: (res: IteratorResult) => void\n      let reject!: (er: unknown) => void\n      const onerr = (er: unknown) => {\n        this.off('data', ondata)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        reject(er)\n      }\n      const ondata = (value: RType) => {\n        this.off('error', onerr)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        this.pause()\n        resolve({ value, done: !!this[EOF] })\n      }\n      const onend = () => {\n        this.off('error', onerr)\n        this.off('data', ondata)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        resolve({ done: true, value: undefined })\n      }\n      const ondestroy = () => onerr(new Error('stream destroyed'))\n      return new Promise>((res, rej) => {\n        reject = rej\n        resolve = res\n        this.once(DESTROYED, ondestroy)\n        this.once('error', onerr)\n        this.once('end', onend)\n        this.once('data', ondata)\n      })\n    }\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.asyncIterator]() {\n        return this\n      },\n      [Symbol.asyncDispose]: async () => {},\n    }\n  }\n\n  /**\n   * Synchronous `for of` iteration.\n   *\n   * The iteration will terminate when the internal buffer runs out, even\n   * if the stream has not yet terminated.\n   */\n  [Symbol.iterator](): Generator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = (): IteratorReturnResult => {\n      this.pause()\n      this.off(ERROR, stop)\n      this.off(DESTROYED, stop)\n      this.off('end', stop)\n      stopped = true\n      return { done: true, value: undefined }\n    }\n\n    const next = (): IteratorResult => {\n      if (stopped) return stop()\n      const value = this.read()\n      return value === null ? stop() : { done: false, value }\n    }\n\n    this.once('end', stop)\n    this.once(ERROR, stop)\n    this.once(DESTROYED, stop)\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.iterator]() {\n        return this\n      },\n      [Symbol.dispose]: () => {},\n    }\n  }\n\n  /**\n   * Destroy a stream, preventing it from being used for any further purpose.\n   *\n   * If the stream has a `close()` method, then it will be called on\n   * destruction.\n   *\n   * After destruction, any attempt to write data, read data, or emit most\n   * events will be ignored.\n   *\n   * If an error argument is provided, then it will be emitted in an\n   * 'error' event.\n   */\n  destroy(er?: unknown) {\n    if (this[DESTROYED]) {\n      if (er) this.emit('error', er)\n      else this.emit(DESTROYED)\n      return this\n    }\n\n    this[DESTROYED] = true\n    this[DISCARDED] = true\n\n    // throw away all buffered data, it's never coming out\n    this[BUFFER].length = 0\n    this[BUFFERLENGTH] = 0\n\n    const wc = this as Minipass & {\n      close?: () => void\n    }\n    if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n    if (er) this.emit('error', er)\n    // if no error to emit, still reject pending promises\n    else this.emit(DESTROYED)\n\n    return this\n  }\n\n  /**\n   * Alias for {@link isStream}\n   *\n   * Former export location, maintained for backwards compatibility.\n   *\n   * @deprecated\n   */\n  static get isStream() {\n    return isStream\n  }\n}\n", "// this is just a very light wrapper around 2 arrays with an offset index\n\nimport type { ParseReturnFiltered } from 'minimatch'\nimport { GLOBSTAR } from 'minimatch'\n\n/**\n * One portion of a parsed minimatch pattern: a string, a Matcher for\n * a portion with magic, or GLOBSTAR for `**`.\n */\nexport type MMPattern = ParseReturnFiltered\n\n/** The Matcher that minimatch makes for a portion with magic. */\nexport type MMMatcher = Exclude\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\nconst customInspect = Symbol.for('nodejs.util.inspect.custom')\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // //?/UNC/host/share/x => ['//?/UNC/host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share', or\n        // '' / '' / '?' / 'UNC' / 'host' / 'share'\n        const n = this.#isLongUNC() ? 6 : 4\n        const proot = this.#patternList.slice(0, n)\n        const groot = this.#globList.slice(0, n)\n        const prest = this.#patternList.slice(n)\n        const grest = this.#globList.slice(n)\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [...proot, ''].join('/')\n        const g = [...groot, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = `${p1 as string}/`\n        const g = `${g1}/`\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  [customInspect]() {\n    return `Pattern <${this.#globList.slice(this.#index).join('/')}>`\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a Matcher, for a portion with magic\n   */\n  isMatcher(): boolean {\n    return typeof this.#patternList[this.#index] === 'object'\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  // the root is //?/UNC/host/share, the same as //host/share\n  #isLongUNC(): boolean {\n    const pl = this.#patternList\n    return (\n      pl[2] === '?' && typeof pl[3] === 'string' && /^unc$/i.test(pl[3])\n    )\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    // the host and share, after //?/UNC/ in a long UNC path\n    const h = this.#isLongUNC() ? 4 : 2\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[h] === 'string' &&\n          !!pl[h] &&\n          typeof pl[h + 1] === 'string' &&\n          !!pl[h + 1])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n", "// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport type { MinimatchOptions } from 'minimatch'\nimport { escape, Minimatch } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport type { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n  /**\n   * The escaped glob for the directory that a pattern starting with\n   * `/` is rooted at, with no trailing `/`.\n   */\n  slashRoot: string\n\n  /**\n   * Patterns that start with `/` (but not drive letters or UNC paths\n   * on Windows) start at the `root` option if it is set, or else at\n   * the root of `cwd`, the same as non-ignored patterns. If `cwd` is\n   * not provided, they start at `/`.\n   */\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      normalize,\n      platform = defaultPlatform,\n      root,\n      windowsPathsNoEscape,\n      allowWindowsEscape,\n      braceExpandMax = 10_000,\n    }: GlobWalkerOpts,\n    cwd?: Path,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    windowsPathsNoEscape =\n      !!windowsPathsNoEscape || allowWindowsEscape === false\n    this.mmopts = {\n      braceExpandMax,\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      normalize,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n      windowsPathsNoEscape,\n    }\n    const slashRoot = cwd?.resolve(root ?? '/').fullpath() ?? '/'\n    this.slashRoot = escape(\n      slashRoot.replace(/\\\\/g, '/').replace(/\\/$/, ''),\n      { magicalBraces: true, windowsPathsNoEscape },\n    )\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const glob =\n        p.root() === '/' ?\n          `${this.slashRoot}/${p.rest()?.globString() ?? ''}`\n        : p.globString()\n      const m = new Minimatch(glob, this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = `${p.fullpath()}/`\n    const relative = `${p.relative() || '.'}/`\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n", "// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport type { MMMatcher, MMPattern, Pattern } from './pattern.js'\nimport type { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path, in\n * this walk step and the steps that led to it.\n *\n * A step only adds to it before it makes the caches for the next\n * steps, so a copy can look up the chain of caches before it, in\n * place of copying their entries. A pattern for a path that a cache\n * up the chain has already seen is added to that cache's set, so that\n * the other steps that share it see it too. Paths are keyed by their\n * full path, because path-scurry can make a new Path object for the\n * same path once its cache of children is full.\n */\nexport class HasWalkedCache {\n  parent?: HasWalkedCache\n  store?: Map>\n  constructor(parent?: HasWalkedCache) {\n    this.parent = parent\n  }\n  copy() {\n    return new HasWalkedCache(this)\n  }\n  // the set for the path in this cache, or the closest one before it\n  #find(fullpath: string): Set | undefined {\n    const set = this.store?.get(fullpath)\n    return set || !this.parent ? set : this.parent.#find(fullpath)\n  }\n\n  hasWalked(target: Path, pattern: Pattern) {\n    return !!this.#find(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.#find(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else\n      (this.store ??= new Map()).set(\n        fullpath,\n        new Set([pattern.globString()]),\n      )\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n * The store maps each path to {@link MatchRecord.ABSOLUTE} and\n * {@link MatchRecord.IF_DIR} flags.\n */\nexport class MatchRecord {\n  static readonly ABSOLUTE = 2\n  static readonly IF_DIR = 1\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n =\n      (absolute ? MatchRecord.ABSOLUTE : 0) |\n      (ifDir ? MatchRecord.IF_DIR : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (typeof p === 'object') {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (typeof p === 'object') {\n          results.testMatcher(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (typeof rp === 'object') {\n        this.testMatcher(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testMatcher(\n    e: Path,\n    p: MMMatcher,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    // an entry name is one path portion, with no `/`\n    if (!p.testUnchecked(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n", "/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport type { Form } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport type { IgnoreLike } from './ignore.js'\nimport { Ignore } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport type { Pattern } from './pattern.js'\nimport { MatchRecord, Processor } from './processor.js'\n\nconst { ABSOLUTE, IF_DIR } = MatchRecord\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  braceExpandMax?: number\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike | ReadonlyArray\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  normalize?: boolean | Form\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Path[]\n  : O extends GWOFileTypesFalse ? string[]\n  : O extends GWOFileTypesUnset ? string[]\n  : (Path | string)[]\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike | ReadonlyArray,\n  opts: GlobWalkerOpts,\n  cwd: Path,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts, cwd)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts, cwd)\n  : (ignore as IgnoreLike)\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => unknown)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts, path)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => unknown) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => unknown) {\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(\n    inPath: Path,\n    ifDir: boolean,\n  ): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    let e: Path\n    if (this.opts.realpath) {\n      rpc = inPath.realpathCached() || (await inPath.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    } else {\n      e = inPath\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(inPath: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    let e: Path\n    if (this.opts.realpath) {\n      rpc = inPath.realpathCached() || inPath.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    } else {\n      e = inPath\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    this.#matchEmitChecked(e, absolute)\n  }\n\n  // emit a match that is known to not be seen or ignored yet\n  #matchEmitChecked(e: Path, absolute: boolean) {\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith(`..${this.#sep}`) ?\n          `.${this.#sep}`\n        : ''\n      this.matchEmit(!rel ? `.${mark}` : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    // matchCheckSync just checked that it is not seen or ignored, and\n    // nothing can have changed since\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.#matchEmitChecked(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => unknown) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) return cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of processor.matches.store) {\n      if (this.#ignored(m)) continue\n      tasks++\n      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>\n        next(),\n      )\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processorx: Processor,\n    cb: () => unknown,\n  ) {\n    const proc = processorx.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of proc.matches.store) {\n      if (this.#ignored(m)) continue\n      tasks++\n      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>\n        next(),\n      )\n    }\n    for (const [target, patterns] of proc.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, proc.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => unknown) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) return cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of processor.matches.store) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    const proc = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of proc.matches.store) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))\n    }\n    for (const [target, patterns] of proc.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, proc.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  // each Path is only emitted once (see GlobUtil.seen), so the results\n  // do not need to be deduped\n  matches: Result[] = []\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.push(e)\n  }\n\n  async walk(): Promise[]> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Result[] {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      void target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n", "import { Minimatch } from 'minimatch'\nimport type { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  for (const p of Array.isArray(pattern) ? pattern : [pattern]) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n", "import { escape, unescape } from 'minimatch'\nimport type { Minipass } from 'minipass'\nimport type { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type { Form } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n"],
+  "mappings": "AAAO,IAAMA,GAAW,CACtBC,EACAC,EACAC,IACE,CACF,IAAMC,EAAKH,aAAa,OAASI,GAAWJ,EAAGE,CAAG,EAAIF,EAChDK,EAAKJ,aAAa,OAASG,GAAWH,EAAGC,CAAG,EAA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OAAO,OAAOR,GAAO,CACvC,KAAMA,GACN,SAAAD,GACA,KAAAQ,GACA,WAAAT,GACA,OAAAM,GACA,eAAAV,GACA,WAAAS,GACA,YAAAD,GACA,QAAAI,GACA,gBAAAL,GACA,YAAAI,GACA,KAAAR,EACA,SAAAY,GACA,OAAAC,EACA,SAAAC,GACD,EACDH,GAAK,KAAOA",
+  "names": ["balanced", "a", "b", "str", "ma", "maybeMatch", "mb", "r", "range", "reg", "m", "begs", "beg", "left", "right", "result", "ai", "bi", "i", "escSlash", "escOpen", "escClose", "escComma", "escPeriod", "escSlashPattern", "escOpenPattern", "escClosePattern", "escCommaPattern", "escPeriodPattern", "slashPattern", "openPattern", "closePattern", "commaPattern", "periodPattern", "EXPANSION_MAX", "EXPANSION_MAX_LENGTH", "EXPANSION_MAX_DEPTH", "EXPANSION_MAX_REWRITES", "numeric", "str", "escapeBraces", "unescapeBraces", "pushAll", "target", "items", "i", "parseCommaParts", "parts", "carry", "m", "balanced", "tail", "pre", "body", "post", "p", "expand", "options", "max", "maxLength", "maxDepth", "maxRewrites", "expand_", "embrace", "isPadded", "el", "lte", "y", "gte", "combine", "acc", "values", "dropEmpties", "out", "length", "v", "expansion", "expandSequence", "isAlphaSequence", "n", "N", "x", "width", "incr", "test", "pad", "c", "need", "z", "depth", "isTop", "rewrites", "firstGroup", "isNumericSequence", "isSequence", "isOptions", "dropsEmpties", "d", "valuesLength", "outer", "j", "expanded", "k", "digit", "a", "b", "prefix", "d", "alts", "s", "fixed", "lo", "hi", "ra", "rb", "zeros", "nines", "out", "last", "nonneg", "width", "len", "numericRange", "loStr", "hiStr", "neg", "posixClasses", "braceEscape", "s", "noMatch", "parseClass", "glob", "position", "nocase", "form", "norm", "c", "n", "pos", "ranges", "negs", "i", "sawStart", "escaping", "negate", "endPos", "rangeStart", "WHILE", "cls", "unip", "neg", "sranges", "snegs", "comb", "MATCH", "extTypes", "lit", "ch", "reEscape", "s", "newFoldRe", "foldCache", "foldRe", "re", "litMatch", "l", "c", "code", "ascii", "tokenize", "p", "nocase", "noext", "form", "mark", "toks", "i", "m", "start", "end", "r", "alts", "numericRange", "e", "consumed", "parseClass", "pair", "pairs", "stack", "tok", "build", "top", "seq", "close", "sub", "normalize", "items", "out", "run", "flush", "it", "a", "compile", "id", "split", "next", "item", "after", "entry", "show", "lines", "seen", "ref", "walk", "indent", "line", "desc", "o", "State", "gen", "sameState", "b", "marks", "size", "Sim", "#marks", "dots", "dotStart", "state", "n", "#visit", "node", "#addThread", "has", "th", "stateKey", "ids", "runs", "DFA_BUDGET", "Dfa", "#start", "#states", "#size", "#plain", "#dotStart", "#sim", "#dotSim", "#make", "#intern", "key", "found", "#clear", "d", "linear", "nodes", "testLinear", "chars", "ni", "ci", "starNi", "starCi", "lengths", "min", "max", "lo", "hi", "itemLengths", "loop", "hasAffix", "lits", "j", "slashOrSurrogate", "surrogate", "codePoints", "noSlash", "Matcher", "#dotsSim", "#literal", "#literalFold", "#literalRe", "#linear", "#wild", "#min", "#max", "#prefix", "#suffix", "#prefixStr", "#suffixStr", "#affix", "#dfa", "#form", "pattern", "options", "literal", "#test", "most", "least", "prefix", "sim", "dfa", "str", "assertValidPattern", "pattern", "escape", "s", "windowsPathsNoEscape", "magicalBraces", "unescape", "s", "windowsPathsNoEscape", "magicalBraces", "minimatch", "p", "pattern", "options", "assertValidPattern", "cachedMinimatch", "cache", "cacheMax", "key", "mm", "Minimatch", "defaultPlatform", "path", "sep", "GLOBSTAR", "filter", "ext", "a", "b", "defaults", "def", "orig", "list", "braceExpand", "expand", "RANGE_MIN", "rangeRe", "match", "f", "globMagic", "classEnd", "start", "i", "sawStart", "c", "literal", "noext", "lit", "close", "body", "extSafe", "depth", "lastSplit", "lastChecked", "portionMatch", "endIndex", "last", "lastStart", "prev", "prevStart", "isDots", "isDrive", "isLongUNC", "uncHost", "h", "host", "share", "walkable", "dot", "dotPortion", "end", "k", "n", "isSep", "s", "nextSep", "from", "lastSep", "PENDING", "#endCheck", "#literalCheck", "#level2", "#form", "#literals", "#shapes", "#endRows", "#matchers", "#pending", "#rangeMark", "#globstarParts", "awe", "drives", "row", "#rootIndex", "r", "lits", "l", "p0", "p1", "p2", "#norm", "part", "#expandBraces", "rawGlobParts", "#slashSplit", "set", "_", "__", "isUNC", "ss", "merged", "len", "groups", "Matcher", "parts", "g", "drop", "first", "rest", "glob", "globParts", "partset", "j", "optimizationLevel", "gs", "root", "#canMatch", "ends", "ROWS", "resolves", "tailStart", "shape", "m", "#walk", "#matchShape", "file", "x", "t", "head", "e", "next", "#cachedSplit", "#split", "isWindows", "preserveMultipleSlashes", "normalize", "#levelTwoFileOptimize", "didSomething", "dd", "braceExpandMax", "splitCells", "maxSplitCells", "gss", "addedCells", "other", "splin", "keys", "rows", "stars", "ok", "changed", "negate", "negateOffset", "#matchRow", "resolved", "partial", "fileStartIndex", "patternStartIndex", "fh", "ph", "fileDrive", "fileUNC", "patternDrive", "patternUNC", "fdi", "pdi", "fd", "pd", "#matchGlobstar", "#matchOne", "fileIndex", "patternIndex", "tail", "segments", "#getGlobstarParts", "headEnd", "fileTailMatch", "sawSome", "#matchGlobStarBodySections", "byStart", "found", "firstgs", "lastgs", "current", "nonGsParts", "nonGsPartsSums", "bodySegments", "fileLength", "bodyIndex", "globStarDepth", "sawTail", "tried", "bs", "need", "after", "sub", "fileEnd", "fi", "pi", "pl", "fl", "code", "mark", "marked", "lo", "hi", "portion", "nocase", "nocaseMagicOnly", "rangeMark", "split", "can", "ff", "filename", "escape", "unescape", "fileURLToPath", "tracingChannel", "channel", "metrics", "tracing", "defaultPerf", "hasSubscribers", "warned", "PROCESS", "emitWarning", "msg", "type", "code", "fn", "shouldWarn", "isPosInt", "n", "getUintArray", "max", "ZeroArray", "size", "Stack", "_Stack", "#constructing", "HeapCls", "s", "LRUCache", "_LRUCache", "#max", "#maxSize", "#dispose", "#onInsert", "#disposeAfter", "#fetchMethod", "#memoMethod", "#perf", "#size", "#calculatedSize", "#keyMap", "#keyList", "#valList", "#next", "#prev", "#head", "#tail", "#free", "#disposed", "#sizes", "#starts", "#ttls", "#autopurgeTimers", "#hasDispose", "#hasFetchMethod", "#hasDisposeAfter", "#hasOnInsert", "c", "p", "#isBackgroundFetch", "k", "index", "options", "context", "#backgroundFetch", "#moveToTail", "#indexes", "#rindexes", "#isStale", "ttl", "ttlResolution", "ttlAutopurge", "updateAgeOnGet", "updateAgeOnHas", "allowStale", "dispose", "onInsert", "disposeAfter", "noDisposeOnSet", "noUpdateTTL", "maxSize", "maxEntrySize", "sizeCalculation", "fetchMethod", "memoMethod", "noDeleteOnFetchRejection", "noDeleteOnStaleGet", "allowStaleOnFetchRejection", "allowStaleOnFetchAbort", "ignoreFetchAbort", "backgroundFetchSize", "perf", "UintArray", "#initializeSizeTracking", "#initializeTTLTracking", "key", "ttls", "starts", "purgeTimers", "#setItemTTL", "start", "setPurgeTimer", "#updateItemAge", "t", "#delete", "getRemainingTTL", "#statusTTL", "status", "cachedNow", "getNow", "age", "sizes", "#removeItemSize", "#requireSize", "v", "#addItemSize", "#evict", "_i", "_s", "_st", "_k", "_v", "i", "#isValidIndex", "getOptions", "value", "#get", "thisp", "deleted", "entry", "remain", "arr", "#set", "setOptions", "result", "bf", "isBF", "oldVal", "oldValue", "setType", "dt", "task", "val", "free", "head", "hasOptions", "#has", "peekOptions", "#peek", "ac", "signal", "fetchOpts", "cb", "updateCache", "aborted", "ignoreAbort", "proceed", "fetchFail", "vl", "eb", "er", "allowStaleAborted", "noDelete", "pcall", "res", "rej", "fmp", "b", "fetchOptions", "ths", "#fetch", "forceRefresh", "stale", "isStale", "staleVal", "#forceFetch", "memoOptions", "#memo", "refresh", "vv", "fetching", "#connect", "reason", "#clear", "pi", "ni", "posix", "win32", "fileURLToPath", "lstatSync", "readdirCB", "readdirSync", "readlinkSync", "rps", "actualFS", "lstat", "readdir", "readlink", "realpath", "EventEmitter", "Stream", "StringDecoder", "proc", "isStream", "s", "Minipass", "isReadable", "isWritable", "EOF", "MAYBE_EMIT_END", "EMITTED_END", "EMITTING_END", "EMITTED_ERROR", "CLOSED", "READ", "FLUSH", "FLUSHCHUNK", "ENCODING", "DECODER", "FLOWING", "PAUSED", "RESUME", "BUFFER", "PIPES", "BUFFERLENGTH", "BUFFERPUSH", "BUFFERSHIFT", "OBJECTMODE", "DESTROYED", "ERROR", "EMITDATA", "EMITEND", "EMITEND2", "ASYNC", "ABORT", "ABORTED", "SIGNAL", "DATALISTENERS", "DISCARDED", "defer", "fn", "nodefer", "isEndish", "ev", "isArrayBufferLike", "b", "isArrayBufferView", "Pipe", "src", "dest", "opts", "_er", "PipeProxyErrors", "er", "isObjectModeOptions", "o", "isEncodingOptions", "args", "options", "signal", "_enc", "_om", "a", "_", "chunk", "encoding", "cb", "n", "ret", "c", "noDrain", "ended", "p", "handler", "h", "data", "buf", "resolve", "reject", "stopped", "stop", "res", "onerr", "ondata", "onend", "ondestroy", "value", "rej", "next", "wc", "realpathSync", "rps", "defaultFS", "lstatSync", "readdirCB", "readdirSync", "readlinkSync", "lstat", "readdir", "readlink", "realpath", "fsFromOption", "fsOption", "actualFS", "uncDriveRegexp", "uncLongRegexp", "uncShareRegexp", "uncToDrive", "rootPath", "longUncRoot", "longDrivePrefix", "longUncPrefix", "eitherSep", "UNKNOWN", "IFIFO", "IFCHR", "IFDIR", "IFBLK", "IFREG", "IFLNK", "IFSOCK", "IFMT", "IFMT_UNKNOWN", "READDIR_CALLED", "LSTAT_CALLED", "ENOTDIR", "ENOENT", "ENOREADLINK", "ENOREALPATH", "ENOCHILD", "TYPEMASK", "entToType", "s", "normalizeCache", "I", "normalize", "c", "n", "normalizeNocaseCache", "normalizeNocase", "ResolveCache", "ChildrenCache", "maxSize", "a", "setAsCwd", "PathBase", "#fs", "#dev", "#mode", "#nlink", "#uid", "#gid", "#rdev", "#blksize", "#ino", "#size", "#blocks", "#atimeMs", "#mtimeMs", "#ctimeMs", "#birthtimeMs", "#atime", "#mtime", "#ctime", "#birthtime", "#matchName", "#depth", "#fullpath", "#fullpathPosix", "#relative", "#relativePosix", "#type", "#children", "#linkTarget", "#realpath", "name", "type", "root", "roots", "nocase", "children", "opts", "path", "dirParts", "#resolveParts", "p", "part", "cached", "pathPart", "fullpath", "pchild", "pv", "fp", "pfpp", "fpp", "ifmt", "target", "read", "linkTarget", "er", "#readlinkFail", "#readdirSuccess", "#markENOENT", "#markChildrenENOENT", "#markENOREALPATH", "#markENOTDIR", "#readdirFail", "code", "#lstatFail", "ter", "#readdirAddChild", "e", "#readdirMaybePromoteChild", "#readdirAddNewChild", "child", "#readdirPromoteChild", "index", "v", "#applyStat", "st", "atime", "atimeMs", "birthtime", "birthtimeMs", "blksize", "blocks", "ctime", "ctimeMs", "dev", "gid", "ino", "mode", "mtime", "mtimeMs", "nlink", "rdev", "size", "uid", "#onReaddirCB", "#readdirCBInFlight", "#callOnReaddirCB", "cbs", "cb", "allowZalgo", "entries", "#asyncReaddirInFlight", "resolve", "res", "dirs", "walkFilter", "rp", "oldCwd", "changed", "PathWin32", "_PathWin32", "win32", "compare", "PathScurryWin32", "PathPosix", "_PathPosix", "_rootPath", "PathScurryBase", "#resolveCache", "#resolvePosixCache", "cwd", "pathImpl", "sep", "childrenCacheSize", "fs", "fileURLToPath", "cwdPath", "split", "prev", "len", "joinSep", "abs", "sawFirst", "l", "paths", "r", "i", "result", "entry", "withFileTypes", "follow", "filter", "results", "walk", "dir", "next", "start", "rej", "options", "Minipass", "queue", "processing", "process", "paused", "onReaddir", "didRealpaths", "promises", "sync", "PathScurryPosix", "posix", "_dir", "PathScurryDarwin", "Path", "PathScurry", "isPatternList", "pl", "isGlobList", "gl", "customInspect", "Pattern", "_Pattern", "#patternList", "#globList", "#index", "#platform", "#rest", "#globString", "#isDrive", "#isUNC", "#isAbsolute", "#followGlobstar", "patternList", "globList", "index", "platform", "#isLongUNC", "proot", "groot", "prest", "grest", "p", "g", "p1", "g1", "GLOBSTAR", "h", "defaultPlatform", "Ignore", "ignored", "nobrace", "nocase", "noext", "noglobstar", "normalize", "platform", "root", "windowsPathsNoEscape", "allowWindowsEscape", "braceExpandMax", "cwd", "slashRoot", "escape", "ign", "mm", "Minimatch", "i", "parsed", "globParts", "p", "Pattern", "glob", "m", "children", "absolute", "fullpath", "fullpaths", "relative", "relatives", "HasWalkedCache", "_HasWalkedCache", "parent", "#find", "fullpath", "set", "target", "pattern", "cached", "MatchRecord", "_MatchRecord", "absolute", "ifDir", "n", "current", "SubWalks", "subs", "p", "k", "Processor", "_Processor", "opts", "hasWalkedCache", "patterns", "processingSet", "t", "root", "rest", "changed", "GLOBSTAR", "rp", "rrest", "tp", "entries", "results", "e", "ep", "ABSOLUTE", "IF_DIR", "MatchRecord", "makeIgnore", "ignore", "opts", "cwd", "Ignore", "GlobUtil", "#onResume", "#ignore", "#sep", "patterns", "path", "m", "#ignored", "#childrenIgnored", "fn", "inPath", "ifDir", "rpc", "e", "s", "target", "absolute", "#matchEmitChecked", "ign", "abs", "mark", "rel", "pre", "p", "cb", "Processor", "processor", "tasks", "next", "n", "t", "childrenCached", "_", "entries", "processorx", "proc", "children", "GlobWalker", "res", "rej", "GlobStream", "Minipass", "defaultPlatform", "Glob", "pattern", "opts", "fileURLToPath", "p", "Scurry", "PathScurryWin32", "PathScurryDarwin", "PathScurryPosix", "PathScurry", "nocaseMagicOnly", "mmo", "mms", "Minimatch", "matchSet", "globParts", "set", "m", "i", "g", "Pattern", "GlobWalker", "GlobStream", "hasMagic", "pattern", "options", "p", "Minimatch", "globStreamSync", "pattern", "options", "Glob", "globStream", "globSync", "glob_", "globIterateSync", "globIterate", "streamSync", "stream", "iterateSync", "iterate", "sync", "glob", "hasMagic", "escape", "unescape"]
 }
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.d.ts b/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.d.ts
index 4e4ed3cdf75d606cc9e43bf293cbf7347da3df99..382c842d76602a609cf2bb9efa9f12b877817950 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.d.ts
@@ -1,5 +1,12 @@
+import type { ParseReturnFiltered } from 'minimatch';
 import { GLOBSTAR } from 'minimatch';
-export type MMPattern = string | RegExp | typeof GLOBSTAR;
+/**
+ * One portion of a parsed minimatch pattern: a string, a Matcher for
+ * a portion with magic, or GLOBSTAR for `**`.
+ */
+export type MMPattern = ParseReturnFiltered;
+/** The Matcher that minimatch makes for a portion with magic. */
+export type MMMatcher = Exclude;
 export type PatternList = [p: MMPattern, ...rest: MMPattern[]];
 export type UNCPatternList = [
     p0: '',
@@ -34,9 +41,9 @@ export declare class Pattern {
      */
     isGlobstar(): boolean;
     /**
-     * true if pattern() returns a regexp
+     * true if pattern() returns a Matcher, for a portion with magic
      */
-    isRegExp(): boolean;
+    isMatcher(): boolean;
     /**
      * The /-joined set of glob parts that make up this pattern
      */
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.d.ts.map
index 2432516afac5e23327340b377c7170f06b179f84..82cecff8f2ff882d4cb849f56875a4f32484709e 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,QAAQ,CAAA;AAGzD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAC9D,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,MAAM;IACV,EAAE,EAAE,MAAM;IACV,GA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;IACH,SAAS,IAAI,OAAO;IAIpB;;OAEG;IACH,UAAU,IAAI,MAAM;IAUpB;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACH,IAAI,IAAI,OAAO,GAAG,IAAI;IAuBtB;;OAEG;IACH,KAAK,IAAI,OAAO;IAsBhB;;OAEG;IACH,OAAO,IAAI,OAAO;IAelB;;OAEG;IACH,UAAU,IAAI,OAAO;IAUrB;;OAEG;IACH,IAAI,IAAI,MAAM;IASd;;;OAGG;IACH,mBAAmB,IAAI,OAAO;IAQ9B;;OAEG;IACH,kBAAkB,IAAI,OAAO;CAM9B"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.js b/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.js
index 2f733da5bf4f903206ee095f46185d587a91e328..7e0205b174100e4cfd801227674771b23eddb269 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.js
@@ -45,19 +45,24 @@ export class Pattern {
             // //host/share => ['//host/share/']
             // //host/share/ => ['//host/share/']
             // //host/share/x => ['//host/share/', 'x']
+            // //?/UNC/host/share/x => ['//?/UNC/host/share/', 'x']
             // /etc => ['/', 'etc']
             // / => ['/']
             if (this.isUNC()) {
-                // '' / '' / 'host' / 'share'
-                const [p0, p1, p2, p3, ...prest] = this.#patternList;
-                const [g0, g1, g2, g3, ...grest] = this.#globList;
+                // '' / '' / 'host' / 'share', or
+                // '' / '' / '?' / 'UNC' / 'host' / 'share'
+                const n = this.#isLongUNC() ? 6 : 4;
+                const proot = this.#patternList.slice(0, n);
+                const groot = this.#globList.slice(0, n);
+                const prest = this.#patternList.slice(n);
+                const grest = this.#globList.slice(n);
                 if (prest[0] === '') {
                     // ends in /
                     prest.shift();
                     grest.shift();
                 }
-                const p = [p0, p1, p2, p3, ''].join('/');
-                const g = [g0, g1, g2, g3, ''].join('/');
+                const p = [...proot, ''].join('/');
+                const g = [...groot, ''].join('/');
                 this.#patternList = [p, ...prest];
                 this.#globList = [g, ...grest];
                 this.length = this.#patternList.length;
@@ -70,8 +75,8 @@ export class Pattern {
                     prest.shift();
                     grest.shift();
                 }
-                const p = p1 + '/';
-                const g = g1 + '/';
+                const p = `${p1}/`;
+                const g = `${g1}/`;
                 this.#patternList = [p, ...prest];
                 this.#globList = [g, ...grest];
                 this.length = this.#patternList.length;
@@ -79,7 +84,7 @@ export class Pattern {
         }
     }
     [customInspect]() {
-        return 'Pattern <' + this.#globList.slice(this.#index).join('/') + '>';
+        return `Pattern <${this.#globList.slice(this.#index).join('/')}>`;
     }
     /**
      * The first entry in the parsed list of patterns
@@ -100,10 +105,10 @@ export class Pattern {
         return this.#patternList[this.#index] === GLOBSTAR;
     }
     /**
-     * true if pattern() returns a regexp
+     * true if pattern() returns a Matcher, for a portion with magic
      */
-    isRegExp() {
-        return this.#patternList[this.#index] instanceof RegExp;
+    isMatcher() {
+        return typeof this.#patternList[this.#index] === 'object';
     }
     /**
      * The /-joined set of glob parts that make up this pattern
@@ -137,11 +142,18 @@ export class Pattern {
         this.#rest.#isDrive = this.#isDrive;
         return this.#rest;
     }
+    // the root is //?/UNC/host/share, the same as //host/share
+    #isLongUNC() {
+        const pl = this.#patternList;
+        return (pl[2] === '?' && typeof pl[3] === 'string' && /^unc$/i.test(pl[3]));
+    }
     /**
      * true if the pattern represents a //unc/path/ on windows
      */
     isUNC() {
         const pl = this.#patternList;
+        // the host and share, after //?/UNC/ in a long UNC path
+        const h = this.#isLongUNC() ? 4 : 2;
         return this.#isUNC !== undefined ?
             this.#isUNC
             : (this.#isUNC =
@@ -149,10 +161,10 @@ export class Pattern {
                     this.#index === 0 &&
                     pl[0] === '' &&
                     pl[1] === '' &&
-                    typeof pl[2] === 'string' &&
-                    !!pl[2] &&
-                    typeof pl[3] === 'string' &&
-                    !!pl[3]);
+                    typeof pl[h] === 'string' &&
+                    !!pl[h] &&
+                    typeof pl[h + 1] === 'string' &&
+                    !!pl[h + 1]);
     }
     // pattern like C:/...
     // split = ['C:', ...]
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.js.map b/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.js.map
index 0f90ed29288d0088570cfb408fdbdb85d1eec7ab..dcb4e98a8a9d31a8096e14be359c066bc1c5ec4b 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/pattern.js.map
@@ -1 +1 @@
-{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAgBpC,MAAM,aAAa,GAAG,CAAC,EAAe,EAAqB,EAAE,CAC3D,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAChB,MAAM,UAAU,GAAG,CAAC,EAAY,EAAkB,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAEnE,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAA;AAE9D;;;GAGG;AACH,MAAM,OAAO,OAAO;IACT,YAAY,CAAa;IACzB,SAAS,CAAU;IACnB,MAAM,CAAQ;IACd,MAAM,CAAQ;IACd,SAAS,CAAiB;IACnC,KAAK,CAAiB;IACtB,WAAW,CAAS;IACpB,QAAQ,CAAU;IAClB,MAAM,CAAU;IAChB,WAAW,CAAU;IACrB,eAAe,GAAY,IAAI,CAAA;IAE/B,YACE,WAAwB,EACxB,QAAkB,EAClB,KAAa,EACb,QAAyB;QAEzB,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,SAAS,CAAC,oBAAoB,CAAC,CAAA;QAC3C,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,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AEG;IACH,kBAAkB;QAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;YAClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF","sourcesContent":["// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\nconst customInspect = Symbol.for('nodejs.util.inspect.custom')\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  [customInspect]() {\n    return 'Pattern <' + this.#globList.slice(this.#index).join('/') + '>'\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAGzE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAwBpC,MAAM,aAAa,GAAG,CAAC,EAAe,EAAqB,EAAE,CAC3D,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAChB,MAAM,UAAU,GAAG,CAAC,EAAY,EAAkB,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAEnE,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAA;AAE9D;;;GAGG;AACH,MAAM,OAAO,OAAO;IACT,YAAY,CAAa;IACzB,SAAS,CAAU;IACnB,MAAM,CAAQ;IACd,MAAM,CAAQ;IACd,SAAS,CAAiB;IACnC,KAAK,CAAiB;IACtB,WAAW,CAAS;IACpB,QAAQ,CAAU;IAClB,MAAM,CAAU;IAChB,WAAW,CAAU;IACrB,eAAe,GAAY,IAAI,CAAA;IAE/B,YACE,WAAwB,EAC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tC,kDAAkD;IAClD,oDAAoD;IACpD;;OAEG;IACH,UAAU;QACR,MAAM,EAAE,GAAG,IAAI,CAAC,YAAY,CAAA;QAC5B,OAAO,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC;YACnC,IAAI,CAAC,WAAW;YAClB,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW;gBACf,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;oBAC/B,IAAI,CAAC,OAAO,EAAE;oBACd,IAAI,CAAC,KAAK,EAAE,CAAC,CAAA;IACrB,CAAC;IAED;;OAEG;IACH,IAAI;QACF,MAAM,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;QAC9B,OAAO,CACH,OAAO,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,CAChE,CAAC,CAAC;YACD,CAAC;YACH,CAAC,CAAC,EAAE,CAAA;IACR,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,CAAC,CACN,IAAI,CAAC,MAAM,KAAK,CAAC;YACjB,CAAC,IAAI,CAAC,UAAU,EAAE;YAClB,CAAC,IAAI,CAAC,eAAe,CACtB,CAAA;IACH,CAAC;IAED;;OAEG;IACH,kBAAkB;QAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;YAClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF","sourcesContent":["// this is just a very light wrapper around 2 arrays with an offset index\n\nimport type { ParseReturnFiltered } from 'minimatch'\nimport { GLOBSTAR } from 'minimatch'\n\n/**\n * One portion of a parsed minimatch pattern: a string, a Matcher for\n * a portion with magic, or GLOBSTAR for `**`.\n */\nexport type MMPattern = ParseReturnFiltered\n\n/** The Matcher that minimatch makes for a portion with magic. */\nexport type MMMatcher = Exclude\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\nconst customInspect = Symbol.for('nodejs.util.inspect.custom')\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // //?/UNC/host/share/x => ['//?/UNC/host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share', or\n        // '' / '' / '?' / 'UNC' / 'host' / 'share'\n        const n = this.#isLongUNC() ? 6 : 4\n        const proot = this.#patternList.slice(0, n)\n        const groot = this.#globList.slice(0, n)\n        const prest = this.#patternList.slice(n)\n        const grest = this.#globList.slice(n)\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [...proot, ''].join('/')\n        const g = [...groot, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = `${p1 as string}/`\n        const g = `${g1}/`\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  [customInspect]() {\n    return `Pattern <${this.#globList.slice(this.#index).join('/')}>`\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a Matcher, for a portion with magic\n   */\n  isMatcher(): boolean {\n    return typeof this.#patternList[this.#index] === 'object'\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  // the root is //?/UNC/host/share, the same as //host/share\n  #isLongUNC(): boolean {\n    const pl = this.#patternList\n    return (\n      pl[2] === '?' && typeof pl[3] === 'string' && /^unc$/i.test(pl[3])\n    )\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    // the host and share, after //?/UNC/ in a long UNC path\n    const h = this.#isLongUNC() ? 4 : 2\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[h] === 'string' &&\n          !!pl[h] &&\n          typeof pl[h + 1] === 'string' &&\n          !!pl[h + 1])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/processor.d.ts b/mac/patchers/desktop/node_modules/glob/dist/esm/processor.d.ts
index ccedfbf2820f7d51167574666a80785ca1b91b07..99f8e14fd17cf261ed2155f464d7e5711f089108 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/processor.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/processor.d.ts
@@ -1,26 +1,39 @@
-import { MMRegExp } from 'minimatch';
-import { Path } from 'path-scurry';
-import { Pattern } from './pattern.js';
-import { GlobWalkerOpts } from './walker.js';
+import type { Path } from 'path-scurry';
+import type { MMMatcher, Pattern } from './pattern.js';
+import type { GlobWalkerOpts } from './walker.js';
 /**
- * A cache of which patterns have been processed for a given Path
+ * A cache of which patterns have been processed for a given Path, in
+ * this walk step and the steps that led to it.
+ *
+ * A step only adds to it before it makes the caches for the next
+ * steps, so a copy can look up the chain of caches before it, in
+ * place of copying their entries. A pattern for a path that a cache
+ * up the chain has already seen is added to that cache's set, so that
+ * the other steps that share it see it too. Paths are keyed by their
+ * full path, because path-scurry can make a new Path object for the
+ * same path once its cache of children is full.
  */
 export declare class HasWalkedCache {
-    store: Map>;
-    constructor(store?: Map>);
+    #private;
+    parent?: HasWalkedCache;
+    store?: Map>;
+    constructor(parent?: HasWalkedCache);
     copy(): HasWalkedCache;
-    hasWalked(target: Path, pattern: Pattern): boolean | undefined;
+    hasWalked(target: Path, pattern: Pattern): boolean;
     storeWalked(target: Path, pattern: Pattern): void;
 }
 /**
  * A record of which paths have been matched in a given walk step,
  * and whether they only are considered a match if they are a directory,
  * and whether their absolute or relative path should be returned.
+ * The store maps each path to {@link MatchRecord.ABSOLUTE} and
+ * {@link MatchRecord.IF_DIR} flags.
  */
 export declare class MatchRecord {
+    static readonly ABSOLUTE = 2;
+    static readonly IF_DIR = 1;
     store: Map;
     add(target: Path, absolute: boolean, ifDir: boolean): void;
-    entries(): [Path, boolean, boolean][];
 }
 /**
  * A collection of patterns that must be processed in a subsequent step
@@ -53,7 +66,7 @@ export declare class Processor {
     child(): Processor;
     filterEntries(parent: Path, entries: Path[]): Processor;
     testGlobstar(e: Path, pattern: Pattern, rest: Pattern | null, absolute: boolean): void;
-    testRegExp(e: Path, p: MMRegExp, rest: Pattern | null, absolute: boolean): void;
+    testMatcher(e: Path, p: MMMatcher, rest: Pattern | null, absolute: boolean): void;
     testString(e: Path, p: string, rest: Pattern | null, absolute: boolean): void;
 }
 //# sourceMappingURL=processor.d.ts.map
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/processor.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/esm/processor.d.ts.map
index aa266fee4a0544a0a8f7fddceb347d7d059643e0..82e512cc8eae57ff198c049c12289bf57fb3ba88 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/processor.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/processor.d.ts.map
@@ -1 +1 @@
-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AAC,EAAE,IAAI,EACP,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IA8CnB,WAAW,CACT,CAAC,EAAE,IAAI,EACP,CAAC,EAAE,SAAS,EACZ,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IAWnB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,EAAE,QAAQ,EAAE,OAAO;CASvE"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/processor.js b/mac/patchers/desktop/node_modules/glob/dist/esm/processor.js
index f874892ffed0c4affb2e0c2c17895e9ebe2a9afd..d84f8f18869407097e2baabd529bf2a79399efc7 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/processor.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/processor.js
@@ -1,48 +1,60 @@
 // synchronous utility for filtering entries and calculating subwalks
 import { GLOBSTAR } from 'minimatch';
 /**
- * A cache of which patterns have been processed for a given Path
+ * A cache of which patterns have been processed for a given Path, in
+ * this walk step and the steps that led to it.
+ *
+ * A step only adds to it before it makes the caches for the next
+ * steps, so a copy can look up the chain of caches before it, in
+ * place of copying their entries. A pattern for a path that a cache
+ * up the chain has already seen is added to that cache's set, so that
+ * the other steps that share it see it too. Paths are keyed by their
+ * full path, because path-scurry can make a new Path object for the
+ * same path once its cache of children is full.
  */
 export class HasWalkedCache {
+    parent;
     store;
-    constructor(store = new Map()) {
-        this.store = store;
+    constructor(parent) {
+        this.parent = parent;
     }
     copy() {
-        return new HasWalkedCache(new Map(this.store));
+        return new HasWalkedCache(this);
+    }
+    // the set for the path in this cache, or the closest one before it
+    #find(fullpath) {
+        const set = this.store?.get(fullpath);
+        return set || !this.parent ? set : this.parent.#find(fullpath);
     }
     hasWalked(target, pattern) {
-        return this.store.get(target.fullpath())?.has(pattern.globString());
+        return !!this.#find(target.fullpath())?.has(pattern.globString());
     }
     storeWalked(target, pattern) {
         const fullpath = target.fullpath();
-        const cached = this.store.get(fullpath);
+        const cached = this.#find(fullpath);
         if (cached)
             cached.add(pattern.globString());
         else
-            this.store.set(fullpath, new Set([pattern.globString()]));
+            (this.store ??= new Map()).set(fullpath, new Set([pattern.globString()]));
     }
 }
 /**
  * A record of which paths have been matched in a given walk step,
  * and whether they only are considered a match if they are a directory,
  * and whether their absolute or relative path should be returned.
+ * The store maps each path to {@link MatchRecord.ABSOLUTE} and
+ * {@link MatchRecord.IF_DIR} flags.
  */
 export class MatchRecord {
+    static ABSOLUTE = 2;
+    static IF_DIR = 1;
     store = new Map();
     add(target, absolute, ifDir) {
-        const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
+        const n = (absolute ? MatchRecord.ABSOLUTE : 0) |
+            (ifDir ? MatchRecord.IF_DIR : 0);
         const current = this.store.get(target);
         this.store.set(target, current === undefined ? n : n & current);
     }
-    // match, absolute, ifdir
-    entries() {
-        return [...this.store.entries()].map(([path, n]) => [
-            path,
-            !!(n & 2),
-            !!(n & 1),
-        ]);
-    }
 }
 /**
  * A collection of patterns that must be processed in a subsequent step
@@ -185,7 +197,7 @@ export class Processor {
                     }
                 }
             }
-            else if (p instanceof RegExp) {
+            else if (typeof p === 'object') {
                 this.subwalks.add(t, pattern);
             }
         }
@@ -213,8 +225,8 @@ export class Processor {
                 if (p === GLOBSTAR) {
                     results.testGlobstar(e, pattern, rest, absolute);
                 }
-                else if (p instanceof RegExp) {
-                    results.testRegExp(e, p, rest, absolute);
+                else if (typeof p === 'object') {
+                    results.testMatcher(e, p, rest, absolute);
                 }
                 else {
                     results.testString(e, p, rest, absolute);
@@ -264,13 +276,14 @@ export class Processor {
                 /* c8 ignore stop */
                 this.subwalks.add(ep, rest);
             }
-            else if (rp instanceof RegExp) {
-                this.testRegExp(e, rp, rest.rest(), absolute);
+            else if (typeof rp === 'object') {
+                this.testMatcher(e, rp, rest.rest(), absolute);
             }
         }
     }
-    testRegExp(e, p, rest, absolute) {
-        if (!p.test(e.name))
+    testMatcher(e, p, rest, absolute) {
+        // an entry name is one path portion, with no `/`
+        if (!p.testUnchecked(e.name))
             return;
         if (!rest) {
             this.matches.add(e, absolute, false);
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/processor.js.map b/mac/patchers/desktop/node_modules/glob/dist/esm/processor.js.map
index 05a832420b8b2fa97eef4e7ab05b6612b5ec17e2..997de2c6f0782fce4608d72874e55e169cb3abb7 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/processor.js.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/processor.js.map
@@ -1 +1 @@
-{"version":3,"file":"processor.js","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAAA,qEAAqE;AAErE,OAAO,EAAE,QAAQ,EAAY,MAAM,WAAW,CAAA;AAK9C;;GAEG;AACH,MAAM,OAAO,cAAc;IACzB,KAAK,CAA0B;IAC/B,YAAY,QAAkC,IAAI,GAAG,EAAE;QACrD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IACD,IAAI;QACF,OAAO,IAAI,cAAc,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,CAAC;IACD,SAAS,CAAC,MAAY,EAAE,OAAgB;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;IACrE,CAAC;IACD,WAAW,CAAC,MAAY,EAAE,OAAgB;QACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAA;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;QACvC,IAAI,MAAM;YAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,UAA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ACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF","sourcesContent":["// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"processor.js","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAAA,qEAAqE;AAErE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAKpC;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,cAAc;IACzB,MAAM,CAAiB;IACvB,KAAK,CAA2B;IAChC,YAAY,MAAuB;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IACD,IAAI;QACF,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,CAAA;IACjC,CAAC;IACD,mEAAmE;IACnE,KAAK,CAAC,QAAgB;QACpB,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAA;QACrC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;IAChE,CAAC;IAED,SAAS,CAAC,MAAY,EAAE,OAAgB;QACtC,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;IACnE,CAAC;IACD,WAAW,CAAC,MAAY,EAAE,OAAgB;QACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAA;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QACnC,IAAI,MAAM;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AC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF","sourcesContent":["// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport type { MMMatcher, MMPattern, Pattern } from './pattern.js'\nimport type { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path, in\n * this walk step and the steps that led to it.\n *\n * A step only adds to it before it makes the caches for the next\n * steps, so a copy can look up the chain of caches before it, in\n * place of copying their entries. A pattern for a path that a cache\n * up the chain has already seen is added to that cache's set, so that\n * the other steps that share it see it too. Paths are keyed by their\n * full path, because path-scurry can make a new Path object for the\n * same path once its cache of children is full.\n */\nexport class HasWalkedCache {\n  parent?: HasWalkedCache\n  store?: Map>\n  constructor(parent?: HasWalkedCache) {\n    this.parent = parent\n  }\n  copy() {\n    return new HasWalkedCache(this)\n  }\n  // the set for the path in this cache, or the closest one before it\n  #find(fullpath: string): Set | undefined {\n    const set = this.store?.get(fullpath)\n    return set || !this.parent ? set : this.parent.#find(fullpath)\n  }\n\n  hasWalked(target: Path, pattern: Pattern) {\n    return !!this.#find(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.#find(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else\n      (this.store ??= new Map()).set(\n        fullpath,\n        new Set([pattern.globString()]),\n      )\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n * The store maps each path to {@link MatchRecord.ABSOLUTE} and\n * {@link MatchRecord.IF_DIR} flags.\n */\nexport class MatchRecord {\n  static readonly ABSOLUTE = 2\n  static readonly IF_DIR = 1\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n =\n      (absolute ? MatchRecord.ABSOLUTE : 0) |\n      (ifDir ? MatchRecord.IF_DIR : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (typeof p === 'object') {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (typeof p === 'object') {\n          results.testMatcher(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (typeof rp === 'object') {\n        this.testMatcher(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testMatcher(\n    e: Path,\n    p: MMMatcher,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    // an entry name is one path portion, with no `/`\n    if (!p.testUnchecked(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/walker.d.ts b/mac/patchers/desktop/node_modules/glob/dist/esm/walker.d.ts
index 499c8f4933857a8720e77b7b96d9842bbd3248ae..120871e839fd7a4f004aa4415fd80c10142c9656 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/walker.d.ts
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/walker.d.ts
@@ -5,18 +5,20 @@
  * @module
  */
 import { Minipass } from 'minipass';
-import { Path } from 'path-scurry';
-import { IgnoreLike } from './ignore.js';
-import { Pattern } from './pattern.js';
+import type { Form } from 'minimatch';
+import type { Path } from 'path-scurry';
+import type { IgnoreLike } from './ignore.js';
+import type { Pattern } from './pattern.js';
 import { Processor } from './processor.js';
 export interface GlobWalkerOpts {
     absolute?: boolean;
     allowWindowsEscape?: boolean;
+    braceExpandMax?: number;
     cwd?: string | URL;
     dot?: boolean;
     dotRelative?: boolean;
     follow?: boolean;
-    ignore?: string | string[] | IgnoreLike;
+    ignore?: string | string[] | IgnoreLike | ReadonlyArray;
     mark?: boolean;
     matchBase?: boolean;
     maxDepth?: number;
@@ -25,6 +27,7 @@ export interface GlobWalkerOpts {
     nodir?: boolean;
     noext?: boolean;
     noglobstar?: boolean;
+    normalize?: boolean | Form;
     platform?: NodeJS.Platform;
     posix?: boolean;
     realpath?: boolean;
@@ -45,7 +48,7 @@ export type GWOFileTypesUnset = GlobWalkerOpts & {
     withFileTypes?: undefined;
 };
 export type Result = O extends GWOFileTypesTrue ? Path : O extends GWOFileTypesFalse ? string : O extends GWOFileTypesUnset ? string : Path | string;
-export type Matches = O extends GWOFileTypesTrue ? Set : O extends GWOFileTypesFalse ? Set : O extends GWOFileTypesUnset ? Set : Set;
+export type Matches = O extends GWOFileTypesTrue ? Path[] : O extends GWOFileTypesFalse ? string[] : O extends GWOFileTypesUnset ? string[] : (Path | string)[];
 export type MatchStream = Minipass, Result>;
 /**
  * basic walking utilities that all the glob walker types use
@@ -64,28 +67,28 @@ export declare abstract class GlobUtil any): void;
-    matchCheck(e: Path, ifDir: boolean): Promise;
+    onResume(fn: () => unknown): void;
+    matchCheck(inPath: Path, ifDir: boolean): Promise;
     matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined;
-    matchCheckSync(e: Path, ifDir: boolean): Path | undefined;
+    matchCheckSync(inPath: Path, ifDir: boolean): Path | undefined;
     abstract matchEmit(p: Result): void;
     abstract matchEmit(p: string | Path): void;
     matchFinish(e: Path, absolute: boolean): void;
     match(e: Path, absolute: boolean, ifDir: boolean): Promise;
     matchSync(e: Path, absolute: boolean, ifDir: boolean): void;
-    walkCB(target: Path, patterns: Pattern[], cb: () => any): void;
-    walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any;
-    walkCB3(target: Path, entries: Path[], processor: Processor, cb: () => any): void;
-    walkCBSync(target: Path, patterns: Pattern[], cb: () => any): void;
-    walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any;
-    walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => any): void;
+    walkCB(target: Path, patterns: Pattern[], cb: () => unknown): unknown;
+    walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => unknown): unknown;
+    walkCB3(target: Path, entries: Path[], processorx: Processor, cb: () => unknown): void;
+    walkCBSync(target: Path, patterns: Pattern[], cb: () => unknown): unknown;
+    walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => unknown): unknown;
+    walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => unknown): void;
 }
 export declare class GlobWalker extends GlobUtil {
-    matches: Set>;
+    matches: Result[];
     constructor(patterns: Pattern[], path: Path, opts: O);
     matchEmit(e: Result): void;
-    walk(): Promise>>;
-    walkSync(): Set>;
+    walk(): Promise[]>;
+    walkSync(): Result[];
 }
 export declare class GlobStream extends GlobUtil {
     results: Minipass, Result>;
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/walker.d.ts.map b/mac/patchers/desktop/node_modules/glob/dist/esm/walker.d.ts.map
index 769957bd59bb1ce67cdf28134be59ca86946c405..8fe892e33fb0f4985939cb08d18cf12e47852eac 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/walker.d.ts.map
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/walker.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"walker.d.ts","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAU,UAAU,EAAE,MAAM,aAAa,CAAA;AAOhD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE1C,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,GAAG,CAAC,EAAE,MAAM,GAAG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,MAAM,EAAE,IAAI,EACZ,OAAO,EAAE,IAAI,EAAE,EACf,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,OAAO;CAoBpB;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IAGnB,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,CAAK;gBAEb,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAIpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAIvB,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;IAiBlC,QAAQ,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE;CAWxB;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;gBAE3B,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAUpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAK7B,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC;IAYxB,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC;CAO7B"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/walker.js b/mac/patchers/desktop/node_modules/glob/dist/esm/walker.js
index 3d68196c4f175f6b314b444e409f9b8a77164963..e9da55d389d280729e98e4b4467ac1d409ed6003 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/walker.js
+++ b/mac/patchers/desktop/node_modules/glob/dist/esm/walker.js
@@ -6,9 +6,10 @@
  */
 import { Minipass } from 'minipass';
 import { Ignore } from './ignore.js';
-import { Processor } from './processor.js';
-const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new Ignore([ignore], opts)
-    : Array.isArray(ignore) ? new Ignore(ignore, opts)
+import { MatchRecord, Processor } from './processor.js';
+const { ABSOLUTE, IF_DIR } = MatchRecord;
+const makeIgnore = (ignore, opts, cwd) => typeof ignore === 'string' ? new Ignore([ignore], opts, cwd)
+    : Array.isArray(ignore) ? new Ignore(ignore, opts, cwd)
         : ignore;
 /**
  * basic walking utilities that all the glob walker types use
@@ -33,7 +34,7 @@ export class GlobUtil {
         this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
         this.includeChildMatches = opts.includeChildMatches !== false;
         if (opts.ignore || !this.includeChildMatches) {
-            this.#ignore = makeIgnore(opts.ignore ?? [], opts);
+            this.#ignore = makeIgnore(opts.ignore ?? [], opts, path);
             if (!this.includeChildMatches &&
                 typeof this.#ignore.add !== 'function') {
                 const m = 'cannot ignore child matches, ignore lacks add() method.';
@@ -74,8 +75,6 @@ export class GlobUtil {
         }
     }
     onResume(fn) {
-        if (this.signal?.aborted)
-            return;
         /* c8 ignore start */
         if (!this.paused) {
             fn();
@@ -87,16 +86,20 @@ export class GlobUtil {
     }
     // do the requisite realpath/stat checking, and return the path
     // to add or undefined to filter it out.
-    async matchCheck(e, ifDir) {
+    async matchCheck(inPath, ifDir) {
         if (ifDir && this.opts.nodir)
             return undefined;
         let rpc;
+        let e;
         if (this.opts.realpath) {
-            rpc = e.realpathCached() || (await e.realpath());
+            rpc = inPath.realpathCached() || (await inPath.realpath());
             if (!rpc)
                 return undefined;
             e = rpc;
         }
+        else {
+            e = inPath;
+        }
         const needStat = e.isUnknown() || this.opts.stat;
         const s = needStat ? await e.lstat() : e;
         if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
@@ -122,16 +125,20 @@ export class GlobUtil {
             e
             : undefined;
     }
-    matchCheckSync(e, ifDir) {
+    matchCheckSync(inPath, ifDir) {
         if (ifDir && this.opts.nodir)
             return undefined;
         let rpc;
+        let e;
         if (this.opts.realpath) {
-            rpc = e.realpathCached() || e.realpathSync();
+            rpc = inPath.realpathCached() || inPath.realpathSync();
             if (!rpc)
                 return undefined;
             e = rpc;
         }
+        else {
+            e = inPath;
+        }
         const needStat = e.isUnknown() || this.opts.stat;
         const s = needStat ? e.lstatSync() : e;
         if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
@@ -145,6 +152,10 @@ export class GlobUtil {
     matchFinish(e, absolute) {
         if (this.#ignored(e))
             return;
+        this.#matchEmitChecked(e, absolute);
+    }
+    // emit a match that is known to not be seen or ignored yet
+    #matchEmitChecked(e, absolute) {
         // we know we have an ignore if this is false, but TS doesn't
         if (!this.includeChildMatches && this.#ignore?.add) {
             const ign = `${e.relativePosix()}/**`;
@@ -163,10 +174,10 @@ export class GlobUtil {
         }
         else {
             const rel = this.opts.posix ? e.relativePosix() : e.relative();
-            const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
-                '.' + this.#sep
+            const pre = this.opts.dotRelative && !rel.startsWith(`..${this.#sep}`) ?
+                `.${this.#sep}`
                 : '';
-            this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
+            this.matchEmit(!rel ? `.${mark}` : pre + rel + mark);
         }
     }
     async match(e, absolute, ifDir) {
@@ -175,14 +186,16 @@ export class GlobUtil {
             this.matchFinish(p, absolute);
     }
     matchSync(e, absolute, ifDir) {
+        // matchCheckSync just checked that it is not seen or ignored, and
+        // nothing can have changed since
         const p = this.matchCheckSync(e, ifDir);
         if (p)
-            this.matchFinish(p, absolute);
+            this.#matchEmitChecked(p, absolute);
     }
     walkCB(target, patterns, cb) {
         /* c8 ignore start */
         if (this.signal?.aborted)
-            cb();
+            return cb();
         /* c8 ignore stop */
         this.walkCB2(target, patterns, new Processor(this.opts), cb);
     }
@@ -190,7 +203,7 @@ export class GlobUtil {
         if (this.#childrenIgnored(target))
             return cb();
         if (this.signal?.aborted)
-            cb();
+            return cb();
         if (this.paused) {
             this.onResume(() => this.walkCB2(target, patterns, processor, cb));
             return;
@@ -204,11 +217,11 @@ export class GlobUtil {
             if (--tasks === 0)
                 cb();
         };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+        for (const [m, n] of processor.matches.store) {
             if (this.#ignored(m))
                 continue;
             tasks++;
-            this.match(m, absolute, ifDir).then(() => next());
+            void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() => next());
         }
         for (const t of processor.subwalkTargets()) {
             if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
@@ -224,29 +237,29 @@ export class GlobUtil {
         }
         next();
     }
-    walkCB3(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
+    walkCB3(target, entries, processorx, cb) {
+        const proc = processorx.filterEntries(target, entries);
         let tasks = 1;
         const next = () => {
             if (--tasks === 0)
                 cb();
         };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+        for (const [m, n] of proc.matches.store) {
             if (this.#ignored(m))
                 continue;
             tasks++;
-            this.match(m, absolute, ifDir).then(() => next());
+            void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() => next());
         }
-        for (const [target, patterns] of processor.subwalks.entries()) {
+        for (const [target, patterns] of proc.subwalks.entries()) {
             tasks++;
-            this.walkCB2(target, patterns, processor.child(), next);
+            this.walkCB2(target, patterns, proc.child(), next);
         }
         next();
     }
     walkCBSync(target, patterns, cb) {
         /* c8 ignore start */
         if (this.signal?.aborted)
-            cb();
+            return cb();
         /* c8 ignore stop */
         this.walkCB2Sync(target, patterns, new Processor(this.opts), cb);
     }
@@ -254,7 +267,7 @@ export class GlobUtil {
         if (this.#childrenIgnored(target))
             return cb();
         if (this.signal?.aborted)
-            cb();
+            return cb();
         if (this.paused) {
             this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
             return;
@@ -268,10 +281,10 @@ export class GlobUtil {
             if (--tasks === 0)
                 cb();
         };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+        for (const [m, n] of processor.matches.store) {
             if (this.#ignored(m))
                 continue;
-            this.matchSync(m, absolute, ifDir);
+            this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR));
         }
         for (const t of processor.subwalkTargets()) {
             if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
@@ -284,31 +297,33 @@ export class GlobUtil {
         next();
     }
     walkCB3Sync(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
+        const proc = processor.filterEntries(target, entries);
         let tasks = 1;
         const next = () => {
             if (--tasks === 0)
                 cb();
         };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+        for (const [m, n] of proc.matches.store) {
             if (this.#ignored(m))
                 continue;
-            this.matchSync(m, absolute, ifDir);
+            this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR));
         }
-        for (const [target, patterns] of processor.subwalks.entries()) {
+        for (const [target, patterns] of proc.subwalks.entries()) {
             tasks++;
-            this.walkCB2Sync(target, patterns, processor.child(), next);
+            this.walkCB2Sync(target, patterns, proc.child(), next);
         }
         next();
     }
 }
 export class GlobWalker extends GlobUtil {
-    matches = new Set();
+    // each Path is only emitted once (see GlobUtil.seen), so the results
+    // do not need to be deduped
+    matches = [];
     constructor(patterns, path, opts) {
         super(patterns, path, opts);
     }
     matchEmit(e) {
-        this.matches.add(e);
+        this.matches.push(e);
     }
     async walk() {
         if (this.signal?.aborted)
@@ -361,7 +376,7 @@ export class GlobStream extends GlobUtil {
     stream() {
         const target = this.path;
         if (target.isUnknown()) {
-            target.lstat().then(() => {
+            void target.lstat().then(() => {
                 this.walkCB(target, this.patterns, () => this.results.end());
             });
         }
diff --git a/mac/patchers/desktop/node_modules/glob/dist/esm/walker.js.map b/mac/patchers/desktop/node_modules/glob/dist/esm/walker.js.map
index daeeda6752713f72f18fae72f9d0113bb6f1b954..1cc987f90cddd3d154ea452e627f14581095ea60 100644
--- a/mac/patchers/desktop/node_modules/glob/dist/esm/walker.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CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF","sourcesContent":["/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Set\n  : O extends GWOFileTypesFalse ? Set\n  : O extends GWOFileTypesUnset ? Set\n  : Set\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts)\n  : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n          '.' + this.#sep\n        : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  matches = new Set>()\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise>> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Set> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAInC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAQpC,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAEvD,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,WAAW,CAAA;AA4DxC,MAAM,UAAU,GAAG,CACjB,MAA8D,EAC9D,IAAoB,EACpB,GAAS,EACG,EAAE,CACd,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC;IAC5D,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC;QACvD,CAAC,CAAE,MAAqB,CAAA;AAE1B;;GAEG;AACH,MAAM,O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AC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF","sourcesContent":["/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport type { Form } from 'minimatch'\nimport type { Path } from 'path-scurry'\nimport type { IgnoreLike } from './ignore.js'\nimport { Ignore } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport type { Pattern } from './pattern.js'\nimport { MatchRecord, Processor } from './processor.js'\n\nconst { ABSOLUTE, IF_DIR } = MatchRecord\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  braceExpandMax?: number\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike | ReadonlyArray\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  normalize?: boolean | Form\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Path[]\n  : O extends GWOFileTypesFalse ? string[]\n  : O extends GWOFileTypesUnset ? string[]\n  : (Path | string)[]\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike | ReadonlyArray,\n  opts: GlobWalkerOpts,\n  cwd: Path,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts, cwd)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts, cwd)\n  : (ignore as IgnoreLike)\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => unknown)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts, path)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => unknown) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => unknown) {\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(\n    inPath: Path,\n    ifDir: boolean,\n  ): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    let e: Path\n    if (this.opts.realpath) {\n      rpc = inPath.realpathCached() || (await inPath.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    } else {\n      e = inPath\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(inPath: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    let e: Path\n    if (this.opts.realpath) {\n      rpc = inPath.realpathCached() || inPath.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    } else {\n      e = inPath\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    this.#matchEmitChecked(e, absolute)\n  }\n\n  // emit a match that is known to not be seen or ignored yet\n  #matchEmitChecked(e: Path, absolute: boolean) {\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith(`..${this.#sep}`) ?\n          `.${this.#sep}`\n        : ''\n      this.matchEmit(!rel ? `.${mark}` : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    // matchCheckSync just checked that it is not seen or ignored, and\n    // nothing can have changed since\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.#matchEmitChecked(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => unknown) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) return cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of processor.matches.store) {\n      if (this.#ignored(m)) continue\n      tasks++\n      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>\n        next(),\n      )\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processorx: Processor,\n    cb: () => unknown,\n  ) {\n    const proc = processorx.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of proc.matches.store) {\n      if (this.#ignored(m)) continue\n      tasks++\n      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>\n        next(),\n      )\n    }\n    for (const [target, patterns] of proc.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, proc.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => unknown) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) return cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of processor.matches.store) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => unknown,\n  ) {\n    const proc = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, n] of proc.matches.store) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))\n    }\n    for (const [target, patterns] of proc.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, proc.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  // each Path is only emitted once (see GlobUtil.seen), so the results\n  // do not need to be deduped\n  matches: Result[] = []\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.push(e)\n  }\n\n  async walk(): Promise[]> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Result[] {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      void target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/glob/package.json b/mac/patchers/desktop/node_modules/glob/package.json
index 03ed19143e0c566f9df9a8d158b303d75a4a60b6..1e5ab2fde8682ea9680ca91b1b1f61e6dba56e40 100644
--- a/mac/patchers/desktop/node_modules/glob/package.json
+++ b/mac/patchers/desktop/node_modules/glob/package.json
@@ -2,9 +2,10 @@
   "author": "Isaac Z. Schlueter  (https://blog.izs.me/)",
   "name": "glob",
   "description": "the most correct and second fastest glob implementation in JavaScript",
-  "version": "13.0.6",
+  "version": "14.0.6",
   "type": "module",
   "tshy": {
+    "selfLink": false,
     "exports": {
       "./package.json": "./package.json",
       "./raw": "./src/index.ts",
@@ -51,42 +52,49 @@
     "url": "git@github.com:isaacs/node-glob.git"
   },
   "files": [
-    "dist"
+    "dist",
+    "src"
   ],
   "scripts": {
     "preversion": "npm test",
-    "postversion": "npm publish",
-    "prepublishOnly": "npm run benchclean; git push origin --follow-tags",
+    "postversion": "git push origin --follow-tags",
     "prepare": "tshy && bash scripts/build.sh",
     "pretest": "npm run prepare",
     "presnap": "npm run prepare",
     "test": "tap",
     "snap": "tap",
-    "format": "prettier --write . --log-level warn",
+    "posttest": "npm run lint",
+    "postsnap": "npm run lint",
+    "format": "prettier --write .",
+    "lint": "oxlint --fix src test",
+    "postlint": "npm run format",
     "typedoc": "typedoc",
     "profclean": "rm -f v8.log profile.txt",
     "test-regen": "npm run profclean && TEST_REGEN=1 node --no-warnings --loader ts-node/esm test/00-setup.ts",
     "prebench": "npm run prepare",
     "bench": "bash benchmark.sh",
+    "bench:docker": "bash bench-docker/bench.sh",
     "preprof": "npm run prepare",
     "prof": "bash prof.sh",
     "benchclean": "node benchclean.cjs"
   },
   "dependencies": {
-    "minimatch": "^10.2.2",
+    "minimatch": "^11.0.5",
     "minipass": "^7.1.3",
-    "path-scurry": "^2.0.2"
+    "path-scurry": "^3.0.0"
   },
   "devDependencies": {
-    "@types/node": "^25.3.0",
-    "esbuild": "^0.27.3",
-    "memfs": "^4.50.0",
+    "@types/node": "^26.6.5",
+    "esbuild": "^0.28.2",
+    "memfs": "^4.80.0",
     "mkdirp": "^3.0.1",
-    "prettier": "^3.6.2",
+    "oxlint": "^1.90.0",
+    "oxlint-tsgolint": "^7.0.2005",
+    "prettier": "^3.9.10",
     "rimraf": "^6.1.3",
-    "tap": "^21.6.1",
-    "tshy": "^3.3.2",
-    "typedoc": "^0.28.17"
+    "tap": "^21.8.0",
+    "tshy": "^4.1.3",
+    "typedoc": "^0.28.20"
   },
   "license": "BlueOak-1.0.0",
   "funding": {
@@ -94,5 +102,12 @@
   },
   "engines": {
     "node": "18 || 20 || >=22"
+  },
+  "allowScripts": {
+    "esbuild@0.28.2": true,
+    "file:../../../../developer/isaacs/minimatch": true,
+    "minimatch": true,
+    "file:../../path-scurry": true,
+    "path-scurry": true
   }
 }
diff --git a/mac/patchers/desktop/node_modules/glob/src/glob.ts b/mac/patchers/desktop/node_modules/glob/src/glob.ts
new file mode 100644
index 0000000000000000000000000000000000000000..019c25c87191b47768452a683922b057e732d9ca
--- /dev/null
+++ b/mac/patchers/desktop/node_modules/glob/src/glob.ts
@@ -0,0 +1,655 @@
+import type { Form, MinimatchOptions } from 'minimatch'
+import { Minimatch } from 'minimatch'
+import type { Minipass } from 'minipass'
+import { fileURLToPath } from 'node:url'
+import type { FSOption, Path } from 'path-scurry'
+import {
+  PathScurry,
+  PathScurryDarwin,
+  PathScurryPosix,
+  PathScurryWin32,
+} from 'path-scurry'
+import type { IgnoreLike } from './ignore.js'
+import { Pattern } from './pattern.js'
+import { GlobStream, GlobWalker } from './walker.js'
+
+export type MatchSet = Minimatch['set']
+export type GlobParts = Exclude
+
+// if no process global, just call it linux.
+// so we default to case-sensitive, / separators
+const defaultPlatform: NodeJS.Platform =
+  (
+    typeof process === 'object' &&
+    process &&
+    typeof process.platform === 'string'
+  ) ?
+    process.platform
+  : 'linux'
+
+/**
+ * A `GlobOptions` object may be provided to any of the exported methods, and
+ * must be provided to the `Glob` constructor.
+ *
+ * All options are optional, boolean, and false by default, unless otherwise
+ * noted.
+ *
+ * All resolved options are added to the Glob object as properties.
+ *
+ * If you are running many `glob` operations, you can pass a Glob object as the
+ * `options` argument to a subsequent operation to share the previously loaded
+ * cache.
+ */
+export interface GlobOptions {
+  /**
+   * Set to `true` to always receive absolute paths for
+   * matched files. Set to `false` to always return relative paths.
+   *
+   * When this option is not set, absolute paths are returned for patterns
+   * that are absolute, and otherwise paths are returned that are relative
+   * to the `cwd` setting.
+   *
+   * This does _not_ make an extra system call to get
+   * the realpath, it only does string path resolution.
+   *
+   * Conflicts with {@link withFileTypes}
+   */
+  absolute?: boolean
+
+  /**
+   * Set to false to enable {@link windowsPathsNoEscape}
+   *
+   * @deprecated
+   */
+  allowWindowsEscape?: boolean
+
+  /**
+   * The current working directory in which to search. Defaults to
+   * `process.cwd()`.
+   *
+   * May be either a string path or a `file://` URL object or string.
+   */
+  cwd?: string | URL
+
+  /**
+   * Include `.dot` files in normal matches and `globstar`
+   * matches. Note that an explicit dot in a portion of the pattern
+   * will always match dot files.
+   */
+  dot?: boolean
+
+  /**
+   * Prepend all relative path strings with `./` (or `.\` on Windows).
+   *
+   * Without this option, returned relative paths are "bare", so instead of
+   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.
+   *
+   * Relative patterns starting with `'../'` are not prepended with `./`, even
+   * if this option is set.
+   */
+  dotRelative?: boolean
+
+  /**
+   * Follow symlinked directories when expanding `**`
+   * patterns. This can result in a lot of duplicate references in
+   * the presence of cyclic links, and make performance quite bad.
+   *
+   * By default, a `**` in a pattern will follow 1 symbolic link if
+   * it is not the first item in the pattern, or none if it is the
+   * first item in the pattern, following the same behavior as Bash.
+   */
+  follow?: boolean
+
+  /**
+   * string or string[], or an object with `ignored` and `childrenIgnored`
+   * methods.
+   *
+   * If a string or string[] is provided, then this is treated as a glob
+   * pattern or array of glob patterns to exclude from matches. To ignore all
+   * children within a directory, as well as the entry itself, append `'/**'`
+   * to the ignore pattern.
+   *
+   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of
+   * any other settings.
+   *
+   * If an object is provided that has `ignored(path)` and/or
+   * `childrenIgnored(path)` methods, then these methods will be called to
+   * determine whether any Path is a match or if its children should be
+   * traversed, respectively.
+   */
+  readonly ignore?: string | string[] | IgnoreLike | ReadonlyArray
+
+  /**
+   * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no
+   * effect if {@link nobrace} is set.
+   *
+   * Only has effect on the {@link hasMagic} function.
+   */
+  magicalBraces?: boolean
+
+  /**
+   * Add a `/` character to directory matches. Note that this requires
+   * additional stat calls in some cases.
+   */
+  mark?: boolean
+
+  /**
+   * Perform a basename-only match if the pattern does not contain any slash
+   * characters. That is, `*.js` would be treated as equivalent to
+   * `**\/*.js`, matching all js files in all directories.
+   */
+  matchBase?: boolean
+
+  /**
+   * Limit the directory traversal to a given depth below the cwd.
+   * Note that this does NOT prevent traversal to sibling folders,
+   * root patterns, and so on. It only limits the maximum folder depth
+   * that the walk will descend, relative to the cwd.
+   */
+  maxDepth?: number
+
+  /**
+   * Do not expand `{a,b}` and `{1..3}` brace sets.
+   */
+  nobrace?: boolean
+
+  /**
+   * Perform a case-insensitive match. This defaults to `true` on macOS and
+   * Windows systems, and `false` on all others.
+   *
+   * **Note** `nocase` should only be explicitly set when it is
+   * known that the filesystem's case sensitivity differs from the
+   * platform default. If set `true` on case-sensitive file
+   * systems, or `false` on case-insensitive file systems, then the
+   * walk may return more or less results than expected.
+   */
+  nocase?: boolean
+
+  /**
+   * Do not match directories, only files. (Note: to match
+   * _only_ directories, put a `/` at the end of the pattern.)
+   */
+  nodir?: boolean
+
+  /**
+   * Do not match "extglob" patterns such as `+(a|b)`.
+   */
+  noext?: boolean
+
+  /**
+   * Normalize unicode in the pattern, and in the file names that it is
+   * matched against, with this form: `'NFC'`, `'NFD'`, `'NFKC'`, or
+   * `'NFKD'`. `true` means `'NFC'`. This is passed to minimatch, so it
+   * applies to the portions of the pattern with magic, and to the
+   * `ignore` patterns.
+   *
+   * The portions of the pattern without magic are looked up with
+   * path-scurry, which already compares the names of the entries
+   * that it knows in their `'NFKD'` form.
+   */
+  normalize?: boolean | Form
+
+  /**
+   * Do not match `**` against multiple filenames. (Ie, treat it as a normal
+   * `*` instead.)
+   *
+   * Conflicts with {@link matchBase}
+   */
+  noglobstar?: boolean
+
+  /**
+   * Defaults to value of `process.platform` if available, or `'linux'` if
+   * not. Setting `platform:'win32'` on non-Windows systems may cause strange
+   * behavior.
+   */
+  platform?: NodeJS.Platform
+
+  /**
+   * Set to true to call `fs.realpath` on all of the
+   * results. In the case of an entry that cannot be resolved, the
+   * entry is omitted. This incurs a slight performance penalty, of
+   * course, because of the added system calls.
+   */
+  realpath?: boolean
+
+  /**
+   *
+   * A string path resolved against the `cwd` option, which
+   * is used as the starting point for absolute patterns that start
+   * with `/`, (but not drive letters or UNC paths on Windows).
+   *
+   * Note that this _doesn't_ necessarily limit the walk to the
+   * `root` directory, and doesn't affect the cwd starting point for
+   * non-absolute patterns. A pattern containing `..` will still be
+   * able to traverse out of the root directory, if it is not an
+   * actual root directory on the filesystem, and any non-absolute
+   * patterns will be matched in the `cwd`. For example, the
+   * pattern `/../*` with `{root:'/some/path'}` will return all
+   * files in `/some`, not all files in `/some/path`. The pattern
+   * `*` with `{root:'/some/path'}` will return all the entries in
+   * the cwd, not the entries in `/some/path`.
+   *
+   * To start absolute and non-absolute patterns in the same
+   * path, you can use `{root:''}`. However, be aware that on
+   * Windows systems, a pattern like `x:/*` or `//host/share/*` will
+   * _always_ start in the `x:/` or `//host/share` directory,
+   * regardless of the `root` setting.
+   */
+  root?: string
+
+  /**
+   * A [PathScurry](http://npm.im/path-scurry) object used
+   * to traverse the file system. If the `nocase` option is set
+   * explicitly, then any provided `scurry` object must match this
+   * setting.
+   */
+  scurry?: PathScurry
+
+  /**
+   * Call `lstat()` on all entries, whether required or not to determine
+   * if it's a valid match. When used with {@link withFileTypes}, this means
+   * that matches will include data such as modified time, permissions, and
+   * so on.  Note that this will incur a performance cost due to the added
+   * system calls.
+   */
+  stat?: boolean
+
+  /**
+   * An AbortSignal which will cancel the Glob walk when
+   * triggered.
+   */
+  signal?: AbortSignal
+
+  /**
+   * Use `\\` as a path separator _only_, and
+   *  _never_ as an escape character. If set, all `\\` characters are
+   *  replaced with `/` in the pattern.
+   *
+   *  Note that this makes it **impossible** to match against paths
+   *  containing literal glob pattern characters, but allows matching
+   *  with patterns constructed using `path.join()` and
+   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)
+   *  behavior of Glob v7 and before on Windows. Please use with
+   *  caution, and be mindful of [the caveat below about Windows
+   *  paths](#windows). (For legacy reasons, this is also set if
+   *  `allowWindowsEscape` is set to the exact value `false`.)
+   */
+  windowsPathsNoEscape?: boolean
+
+  /**
+   * Return [PathScurry](http://npm.im/path-scurry)
+   * `Path` objects instead of strings. These are similar to a
+   * NodeJS `Dirent` object, but with additional methods and
+   * properties.
+   *
+   * Conflicts with {@link absolute}
+   */
+  withFileTypes?: boolean
+
+  /**
+   * An fs implementation to override some or all of the defaults.  See
+   * http://npm.im/path-scurry for details about what can be overridden.
+   */
+  fs?: FSOption
+
+  /**
+   * Return `/` delimited paths, even on Windows.
+   *
+   * On posix systems, this has no effect.  But, on Windows, it means that
+   * paths will be `/` delimited, and absolute paths will be their full
+   * resolved UNC forms, eg instead of `'C:\\foo\\bar'`, it would return
+   * `'//?/C:/foo/bar'`
+   */
+  posix?: boolean
+
+  /**
+   * Do not match any children of any matches. For example, the pattern
+   * `**\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.
+   *
+   * This is especially useful for cases like "find all `node_modules`
+   * folders, but not the ones in `node_modules`".
+   *
+   * In order to support this, the `Ignore` implementation must support an
+   * `add(pattern: string)` method. If using the default `Ignore` class, then
+   * this is fine, but if this is set to `false`, and a custom `Ignore` is
+   * provided that does not have an `add()` method, then it will throw an
+   * error.
+   *
+   * **Caveat** It *only* ignores matches that would be a descendant of a
+   * previous match, and only if that descendant is matched *after* the
+   * ancestor is encountered. Since the file system walk happens in
+   * indeterminate order, it's possible that a match will already be added
+   * before its ancestor, if multiple or braced patterns are used.
+   *
+   * For example:
+   *
+   * ```ts
+   * const results = await glob([
+   *   // likely to match first, since it's just a stat
+   *   'a/b/c/d/e/f',
+   *
+   *   // this pattern is more complicated! It must to various readdir()
+   *   // calls and test the results against a regular expression, and that
+   *   // is certainly going to take a little bit longer.
+   *   //
+   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too
+   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.
+   *   'a/[bdf]/?/[a-z]/*',
+   * ], { includeChildMatches: false })
+   * ```
+   *
+   * It's best to only set this to `false` if you can be reasonably sure that
+   * no components of the pattern will potentially match one another's file
+   * system descendants, or if the occasional included child entry will not
+   * cause problems.
+   *
+   * @default true
+   */
+  includeChildMatches?: boolean
+
+  /**
+   * max number of `{...}` patterns to expand. Default `1_000`.
+   *
+   * Note: this is much less than minimatch's default of `100_000`,
+   * because Glob has higher memory requirements due to walking
+   * the file system tree.
+   */
+  braceExpandMax?: number
+}
+
+export type GlobOptionsWithFileTypesTrue = GlobOptions & {
+  withFileTypes: true
+  // string options not relevant if returning Path objects.
+  absolute?: undefined
+  mark?: undefined
+  posix?: undefined
+}
+
+export type GlobOptionsWithFileTypesFalse = GlobOptions & {
+  withFileTypes?: false
+}
+
+export type GlobOptionsWithFileTypesUnset = GlobOptions & {
+  withFileTypes?: undefined
+}
+
+export type Result =
+  Opts extends GlobOptionsWithFileTypesTrue ? Path
+  : Opts extends GlobOptionsWithFileTypesFalse ? string
+  : Opts extends GlobOptionsWithFileTypesUnset ? string
+  : string | Path
+export type Results = Result[]
+
+export type FileTypes =
+  Opts extends GlobOptionsWithFileTypesTrue ? true
+  : Opts extends GlobOptionsWithFileTypesFalse ? false
+  : Opts extends GlobOptionsWithFileTypesUnset ? false
+  : boolean
+
+/**
+ * An object that can perform glob pattern traversals.
+ */
+export class Glob implements GlobOptions {
+  absolute?: boolean
+  cwd: string
+  root?: string
+  dot: boolean
+  dotRelative: boolean
+  follow: boolean
+  ignore?: string | string[] | IgnoreLike | ReadonlyArray
+  magicalBraces: boolean
+  mark?: boolean
+  matchBase: boolean
+  maxDepth: number
+  nobrace: boolean
+  nocase: boolean
+  nodir: boolean
+  noext: boolean
+  noglobstar: boolean
+  pattern: string[] | ReadonlyArray
+  platform: NodeJS.Platform
+  realpath: boolean
+  scurry: PathScurry
+  stat: boolean
+  signal?: AbortSignal
+  windowsPathsNoEscape: boolean
+  withFileTypes: FileTypes
+  includeChildMatches: boolean
+
+  /**
+   * The options provided to the constructor.
+   */
+  opts: Opts
+
+  /**
+   * An array of parsed immutable {@link Pattern} objects.
+   */
+  patterns: Pattern[]
+
+  /**
+   * All options are stored as properties on the `Glob` object.
+   *
+   * See {@link GlobOptions} for full options descriptions.
+   *
+   * Note that a previous `Glob` object can be passed as the
+   * `GlobOptions` to another `Glob` instantiation to re-use settings
+   * and caches with a new pattern.
+   *
+   * Traversal functions can be called multiple times to run the walk
+   * again.
+   */
+  constructor(pattern: string | string[], opts: Opts) {
+    /* c8 ignore start */
+    if (!opts) throw new TypeError('glob options required')
+    /* c8 ignore stop */
+    this.withFileTypes = !!opts.withFileTypes as FileTypes
+    this.signal = opts.signal
+    this.follow = !!opts.follow
+    this.dot = !!opts.dot
+    this.dotRelative = !!opts.dotRelative
+    this.nodir = !!opts.nodir
+    this.mark = !!opts.mark
+    if (!opts.cwd) {
+      this.cwd = ''
+    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {
+      opts.cwd = fileURLToPath(opts.cwd)
+    }
+    this.cwd = opts.cwd || ''
+    this.root = opts.root
+    this.magicalBraces = !!opts.magicalBraces
+    this.nobrace = !!opts.nobrace
+    this.noext = !!opts.noext
+    this.realpath = !!opts.realpath
+    this.absolute = opts.absolute
+    this.includeChildMatches = opts.includeChildMatches !== false
+
+    this.noglobstar = !!opts.noglobstar
+    this.matchBase = !!opts.matchBase
+    this.maxDepth =
+      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity
+    this.stat = !!opts.stat
+    this.ignore = opts.ignore
+
+    if (this.withFileTypes && this.absolute !== undefined) {
+      throw new Error('cannot set absolute and withFileTypes:true')
+    }
+
+    let p: string[] = typeof pattern === 'string' ? [pattern] : pattern
+
+    this.windowsPathsNoEscape =
+      !!opts.windowsPathsNoEscape ||
+      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===
+        false
+
+    if (this.windowsPathsNoEscape) {
+      p = p.map(p => p.replace(/\\/g, '/'))
+    }
+
+    if (this.matchBase) {
+      if (opts.noglobstar) {
+        throw new TypeError('base matching requires globstar')
+      }
+      p = p.map(p => (p.includes('/') ? p : `./**/${p}`))
+    }
+
+    this.pattern = p
+
+    this.platform = opts.platform || defaultPlatform
+    this.opts = { ...opts, platform: this.platform }
+    if (opts.scurry) {
+      this.scurry = opts.scurry
+      if (
+        opts.nocase !== undefined &&
+        opts.nocase !== opts.scurry.nocase
+      ) {
+        throw new Error('nocase option contradicts provided scurry option')
+      }
+    } else {
+      const Scurry =
+        opts.platform === 'win32' ? PathScurryWin32
+        : opts.platform === 'darwin' ? PathScurryDarwin
+        : opts.platform ? PathScurryPosix
+        : PathScurry
+      this.scurry = new Scurry(this.cwd, {
+        nocase: opts.nocase,
+        fs: opts.fs,
+      })
+    }
+    this.nocase = this.scurry.nocase
+
+    // If you do nocase:true on a case-sensitive file system, then
+    // we need to use regexps instead of strings for non-magic
+    // path portions, because statting `aBc` won't return results
+    // for the file `AbC` for example.
+    const nocaseMagicOnly =
+      this.platform === 'darwin' || this.platform === 'win32'
+
+    const mmo: MinimatchOptions = {
+      braceExpandMax: 10_000,
+      ...opts,
+      dot: this.dot,
+      matchBase: this.matchBase,
+      nobrace: this.nobrace,
+      // default nocase based on platform
+      nocase: this.nocase,
+      nocaseMagicOnly,
+      nocomment: true,
+      noext: this.noext,
+      nonegate: true,
+      optimizationLevel: 2,
+      platform: this.platform,
+      windowsPathsNoEscape: this.windowsPathsNoEscape,
+    }
+
+    const mms = this.pattern.map(p => new Minimatch(p, mmo))
+    const [matchSet, globParts] = mms.reduce(
+      (set: [MatchSet, GlobParts], m) => {
+        set[0].push(...m.set)
+        set[1].push(...m.globParts)
+        return set
+      },
+      [[], []],
+    )
+    this.patterns = matchSet.map((set, i) => {
+      const g = globParts[i]
+      /* c8 ignore start */
+      if (!g) throw new Error('invalid pattern object')
+      /* c8 ignore stop */
+      return new Pattern(set, g, 0, this.platform)
+    })
+  }
+
+  /**
+   * Returns a Promise that resolves to the results array.
+   */
+  async walk(): Promise>
+  async walk(): Promise<(string | Path)[]> {
+    // Walkers always return array of Path objects, so we just have to
+    // coerce them into the right shape.  It will have already called
+    // realpath() if the option was set to do so, so we know that's cached.
+    // start out knowing the cwd, at least
+    return await new GlobWalker(this.patterns, this.scurry.cwd, {
+      ...this.opts,
+      maxDepth:
+        this.maxDepth !== Infinity ?
+          this.maxDepth + this.scurry.cwd.depth()
+        : Infinity,
+      platform: this.platform,
+      nocase: this.nocase,
+      includeChildMatches: this.includeChildMatches,
+    }).walk()
+  }
+
+  /**
+   * synchronous {@link Glob.walk}
+   */
+  walkSync(): Results
+  walkSync(): (string | Path)[] {
+    return new GlobWalker(this.patterns, this.scurry.cwd, {
+      ...this.opts,
+      maxDepth:
+        this.maxDepth !== Infinity ?
+          this.maxDepth + this.scurry.cwd.depth()
+        : Infinity,
+      platform: this.platform,
+      nocase: this.nocase,
+      includeChildMatches: this.includeChildMatches,
+    }).walkSync()
+  }
+
+  /**
+   * Stream results asynchronously.
+   */
+  stream(): Minipass, Result>
+  stream(): Minipass {
+    return new GlobStream(this.patterns, this.scurry.cwd, {
+      ...this.opts,
+      maxDepth:
+        this.maxDepth !== Infinity ?
+          this.maxDepth + this.scurry.cwd.depth()
+        : Infinity,
+      platform: this.platform,
+      nocase: this.nocase,
+      includeChildMatches: this.includeChildMatches,
+    }).stream()
+  }
+
+  /**
+   * Stream results synchronously.
+   */
+  streamSync(): Minipass, Result>
+  streamSync(): Minipass {
+    return new GlobStream(this.patterns, this.scurry.cwd, {
+      ...this.opts,
+      maxDepth:
+        this.maxDepth !== Infinity ?
+          this.maxDepth + this.scurry.cwd.depth()
+        : Infinity,
+      platform: this.platform,
+      nocase: this.nocase,
+      includeChildMatches: this.includeChildMatches,
+    }).streamSync()
+  }
+
+  /**
+   * Default sync iteration function. Returns a Generator that
+   * iterates over the results.
+   */
+  iterateSync(): Generator, void, void> {
+    return this.streamSync()[Symbol.iterator]()
+  }
+  [Symbol.iterator]() {
+    return this.iterateSync()
+  }
+
+  /**
+   * Default async iteration function. Returns an AsyncGenerator that
+   * iterates over the results.
+   */
+  iterate(): AsyncGenerator, void, void> {
+    return this.stream()[Symbol.asyncIterator]()
+  }
+  [Symbol.asyncIterator]() {
+    return this.iterate()
+  }
+}
diff --git a/mac/patchers/desktop/node_modules/glob/src/has-magic.ts b/mac/patchers/desktop/node_modules/glob/src/has-magic.ts
new file mode 100644
index 0000000000000000000000000000000000000000..8a27b896b496a2bedd5aa3efa77ccdfbcadd51e4
--- /dev/null
+++ b/mac/patchers/desktop/node_modules/glob/src/has-magic.ts
@@ -0,0 +1,23 @@
+import { Minimatch } from 'minimatch'
+import type { GlobOptions } from './glob.js'
+
+/**
+ * Return true if the patterns provided contain any magic glob characters,
+ * given the options provided.
+ *
+ * Brace expansion is not considered "magic" unless the `magicalBraces` option
+ * is set, as brace expansion just turns one string into an array of strings.
+ * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
+ * `'xby'` both do not contain any magic glob characters, and it's treated the
+ * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
+ * is in the options, brace expansion _is_ treated as a pattern having magic.
+ */
+export const hasMagic = (
+  pattern: string | string[],
+  options: GlobOptions = {},
+): boolean => {
+  for (const p of Array.isArray(pattern) ? pattern : [pattern]) {
+    if (new Minimatch(p, options).hasMagic()) return true
+  }
+  return false
+}
diff --git a/mac/patchers/desktop/node_modules/glob/src/ignore.ts b/mac/patchers/desktop/node_modules/glob/src/ignore.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5e3b95ae6c2fb464e6092ce62eb9af372bcbc5fd
--- /dev/null
+++ b/mac/patchers/desktop/node_modules/glob/src/ignore.ts
@@ -0,0 +1,164 @@
+// give it a pattern, and it'll be able to tell you if
+// a given path should be ignored.
+// Ignoring a path ignores its children if the pattern ends in /**
+// Ignores are always parsed in dot:true mode
+
+import type { MinimatchOptions } from 'minimatch'
+import { escape, Minimatch } from 'minimatch'
+import type { Path } from 'path-scurry'
+import { Pattern } from './pattern.js'
+import type { GlobWalkerOpts } from './walker.js'
+
+export interface IgnoreLike {
+  ignored?: (p: Path) => boolean
+  childrenIgnored?: (p: Path) => boolean
+  add?: (ignore: string) => void
+}
+
+const defaultPlatform: NodeJS.Platform =
+  (
+    typeof process === 'object' &&
+    process &&
+    typeof process.platform === 'string'
+  ) ?
+    process.platform
+  : 'linux'
+
+/**
+ * Class used to process ignored patterns
+ */
+export class Ignore implements IgnoreLike {
+  relative: Minimatch[]
+  relativeChildren: Minimatch[]
+  absolute: Minimatch[]
+  absoluteChildren: Minimatch[]
+  platform: NodeJS.Platform
+  mmopts: MinimatchOptions
+  /**
+   * The escaped glob for the directory that a pattern starting with
+   * `/` is rooted at, with no trailing `/`.
+   */
+  slashRoot: string
+
+  /**
+   * Patterns that start with `/` (but not drive letters or UNC paths
+   * on Windows) start at the `root` option if it is set, or else at
+   * the root of `cwd`, the same as non-ignored patterns. If `cwd` is
+   * not provided, they start at `/`.
+   */
+  constructor(
+    ignored: string[],
+    {
+      nobrace,
+      nocase,
+      noext,
+      noglobstar,
+      normalize,
+      platform = defaultPlatform,
+      root,
+      windowsPathsNoEscape,
+      allowWindowsEscape,
+      braceExpandMax = 10_000,
+    }: GlobWalkerOpts,
+    cwd?: Path,
+  ) {
+    this.relative = []
+    this.absolute = []
+    this.relativeChildren = []
+    this.absoluteChildren = []
+    this.platform = platform
+    windowsPathsNoEscape =
+      !!windowsPathsNoEscape || allowWindowsEscape === false
+    this.mmopts = {
+      braceExpandMax,
+      dot: true,
+      nobrace,
+      nocase,
+      noext,
+      noglobstar,
+      normalize,
+      optimizationLevel: 2,
+      platform,
+      nocomment: true,
+      nonegate: true,
+      windowsPathsNoEscape,
+    }
+    const slashRoot = cwd?.resolve(root ?? '/').fullpath() ?? '/'
+    this.slashRoot = escape(
+      slashRoot.replace(/\\/g, '/').replace(/\/$/, ''),
+      { magicalBraces: true, windowsPathsNoEscape },
+    )
+    for (const ign of ignored) this.add(ign)
+  }
+
+  add(ign: string) {
+    // this is a little weird, but it gives us a clean set of optimized
+    // minimatch matchers, without getting tripped up if one of them
+    // ends in /** inside a brace section, and it's only inefficient at
+    // the start of the walk, not along it.
+    // It'd be nice if the Pattern class just had a .test() method, but
+    // handling globstars is a bit of a pita, and that code already lives
+    // in minimatch anyway.
+    // Another way would be if maybe Minimatch could take its set/globParts
+    // as an option, and then we could at least just use Pattern to test
+    // for absolute-ness.
+    // Yet another way, Minimatch could take an array of glob strings, and
+    // a cwd option, and do the right thing.
+    const mm = new Minimatch(ign, this.mmopts)
+    for (let i = 0; i < mm.set.length; i++) {
+      const parsed = mm.set[i]
+      const globParts = mm.globParts[i]
+      /* c8 ignore start */
+      if (!parsed || !globParts) {
+        throw new Error('invalid pattern object')
+      }
+      // strip off leading ./ portions
+      // https://github.com/isaacs/node-glob/issues/570
+      while (parsed[0] === '.' && globParts[0] === '.') {
+        parsed.shift()
+        globParts.shift()
+      }
+      /* c8 ignore stop */
+      const p = new Pattern(parsed, globParts, 0, this.platform)
+      const glob =
+        p.root() === '/' ?
+          `${this.slashRoot}/${p.rest()?.globString() ?? ''}`
+        : p.globString()
+      const m = new Minimatch(glob, this.mmopts)
+      const children = globParts[globParts.length - 1] === '**'
+      const absolute = p.isAbsolute()
+      if (absolute) this.absolute.push(m)
+      else this.relative.push(m)
+      if (children) {
+        if (absolute) this.absoluteChildren.push(m)
+        else this.relativeChildren.push(m)
+      }
+    }
+  }
+
+  ignored(p: Path): boolean {
+    const fullpath = p.fullpath()
+    const fullpaths = `${fullpath}/`
+    const relative = p.relative() || '.'
+    const relatives = `${relative}/`
+    for (const m of this.relative) {
+      if (m.match(relative) || m.match(relatives)) return true
+    }
+    for (const m of this.absolute) {
+      if (m.match(fullpath) || m.match(fullpaths)) return true
+    }
+    return false
+  }
+
+  childrenIgnored(p: Path): boolean {
+    const fullpath = `${p.fullpath()}/`
+    const relative = `${p.relative() || '.'}/`
+    for (const m of this.relativeChildren) {
+      if (m.match(relative)) return true
+    }
+    for (const m of this.absoluteChildren) {
+      if (m.match(fullpath)) return true
+    }
+    return false
+  }
+}
diff --git a/mac/patchers/desktop/node_modules/glob/src/index.ts b/mac/patchers/desktop/node_modules/glob/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..4adb8e373bf785a46c8e92daaafedf9cd1196208
--- /dev/null
+++ b/mac/patchers/desktop/node_modules/glob/src/index.ts
@@ -0,0 +1,225 @@
+import { escape, unescape } from 'minimatch'
+import type { Minipass } from 'minipass'
+import type { Path } from 'path-scurry'
+import type {
+  GlobOptions,
+  GlobOptionsWithFileTypesFalse,
+  GlobOptionsWithFileTypesTrue,
+  GlobOptionsWithFileTypesUnset,
+} from './glob.js'
+import { Glob } from './glob.js'
+import { hasMagic } from './has-magic.js'
+
+export { escape, unescape } from 'minimatch'
+export type { Form } from 'minimatch'
+export type {
+  FSOption,
+  Path,
+  WalkOptions,
+  WalkOptionsWithFileTypesTrue,
+  WalkOptionsWithFileTypesUnset,
+} from 'path-scurry'
+export { Glob } from './glob.js'
+export type {
+  GlobOptions,
+  GlobOptionsWithFileTypesFalse,
+  GlobOptionsWithFileTypesTrue,
+  GlobOptionsWithFileTypesUnset,
+} from './glob.js'
+export { hasMagic } from './has-magic.js'
+export { Ignore } from './ignore.js'
+export type { IgnoreLike } from './ignore.js'
+export type { MatchStream } from './walker.js'
+
+/**
+ * Syncronous form of {@link globStream}. Will read all the matches as fast as
+ * you consume them, even all in a single tick if you consume them immediately,
+ * but will still respond to backpressure if they're not consumed immediately.
+ */
+export function globStreamSync(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesTrue,
+): Minipass
+export function globStreamSync(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesFalse,
+): Minipass
+export function globStreamSync(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesUnset,
+): Minipass
+export function globStreamSync(
+  pattern: string | string[],
+  options: GlobOptions,
+): Minipass | Minipass
+export function globStreamSync(
+  pattern: string | string[],
+  options: GlobOptions = {},
+) {
+  return new Glob(pattern, options).streamSync()
+}
+
+/**
+ * Return a stream that emits all the strings or `Path` objects and
+ * then emits `end` when completed.
+ */
+export function globStream(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesFalse,
+): Minipass
+export function globStream(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesTrue,
+): Minipass
+export function globStream(
+  pattern: string | string[],
+  options?: GlobOptionsWithFileTypesUnset | undefined,
+): Minipass
+export function globStream(
+  pattern: string | string[],
+  options: GlobOptions,
+): Minipass | Minipass
+export function globStream(
+  pattern: string | string[],
+  options: GlobOptions = {},
+) {
+  return new Glob(pattern, options).stream()
+}
+
+/**
+ * Synchronous form of {@link glob}
+ */
+export function globSync(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesFalse,
+): string[]
+export function globSync(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesTrue,
+): Path[]
+export function globSync(
+  pattern: string | string[],
+  options?: GlobOptionsWithFileTypesUnset | undefined,
+): string[]
+export function globSync(
+  pattern: string | string[],
+  options: GlobOptions,
+): Path[] | string[]
+export function globSync(
+  pattern: string | string[],
+  options: GlobOptions = {},
+) {
+  return new Glob(pattern, options).walkSync()
+}
+
+/**
+ * Perform an asynchronous glob search for the pattern(s) specified. Returns
+ * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the
+ * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for
+ * full option descriptions.
+ */
+async function glob_(
+  pattern: string | string[],
+  options?: GlobOptionsWithFileTypesUnset | undefined,
+): Promise
+async function glob_(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesTrue,
+): Promise
+async function glob_(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesFalse,
+): Promise
+async function glob_(
+  pattern: string | string[],
+  options: GlobOptions,
+): Promise
+async function glob_(
+  pattern: string | string[],
+  options: GlobOptions = {},
+) {
+  return new Glob(pattern, options).walk()
+}
+
+/**
+ * Return a sync iterator for walking glob pattern matches.
+ */
+export function globIterateSync(
+  pattern: string | string[],
+  options?: GlobOptionsWithFileTypesUnset | undefined,
+): Generator
+export function globIterateSync(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesTrue,
+): Generator
+export function globIterateSync(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesFalse,
+): Generator
+export function globIterateSync(
+  pattern: string | string[],
+  options: GlobOptions,
+): Generator | Generator
+export function globIterateSync(
+  pattern: string | string[],
+  options: GlobOptions = {},
+) {
+  return new Glob(pattern, options).iterateSync()
+}
+
+/**
+ * Return an async iterator for walking glob pattern matches.
+ */
+export function globIterate(
+  pattern: string | string[],
+  options?: GlobOptionsWithFileTypesUnset | undefined,
+): AsyncGenerator
+export function globIterate(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesTrue,
+): AsyncGenerator
+export function globIterate(
+  pattern: string | string[],
+  options: GlobOptionsWithFileTypesFalse,
+): AsyncGenerator
+export function globIterate(
+  pattern: string | string[],
+  options: GlobOptions,
+): AsyncGenerator | AsyncGenerator
+export function globIterate(
+  pattern: string | string[],
+  options: GlobOptions = {},
+) {
+  return new Glob(pattern, options).iterate()
+}
+
+// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc
+export const streamSync = globStreamSync
+export const stream = Object.assign(globStream, { sync: globStreamSync })
+export const iterateSync = globIterateSync
+export const iterate = Object.assign(globIterate, {
+  sync: globIterateSync,
+})
+export const sync = Object.assign(globSync, {
+  stream: globStreamSync,
+  iterate: globIterateSync,
+})
+
+export const glob = Object.assign(glob_, {
+  glob: glob_,
+  globSync,
+  sync,
+  globStream,
+  stream,
+  globStreamSync,
+  streamSync,
+  globIterate,
+  iterate,
+  globIterateSync,
+  iterateSync,
+  Glob,
+  hasMagic,
+  escape,
+  unescape,
+})
+glob.glob = glob
diff --git a/mac/patchers/desktop/node_modules/glob/src/pattern.ts b/mac/patchers/desktop/node_modules/glob/src/pattern.ts
new file mode 100644
index 0000000000000000000000000000000000000000..472513df902898767645ab764e7de0973d37157b
--- /dev/null
+++ b/mac/patchers/desktop/node_modules/glob/src/pattern.ts
@@ -0,0 +1,286 @@
+// this is just a very light wrapper around 2 arrays with an offset index
+
+import type { ParseReturnFiltered } from 'minimatch'
+import { GLOBSTAR } from 'minimatch'
+
+/**
+ * One portion of a parsed minimatch pattern: a string, a Matcher for
+ * a portion with magic, or GLOBSTAR for `**`.
+ */
+export type MMPattern = ParseReturnFiltered
+
+/** The Matcher that minimatch makes for a portion with magic. */
+export type MMMatcher = Exclude
+
+// an array of length >= 1
+export type PatternList = [p: MMPattern, ...rest: MMPattern[]]
+export type UNCPatternList = [
+  p0: '',
+  p1: '',
+  p2: string,
+  p3: string,
+  ...rest: MMPattern[],
+]
+export type DrivePatternList = [p0: string, ...rest: MMPattern[]]
+export type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]
+export type GlobList = [p: string, ...rest: string[]]
+
+const isPatternList = (pl: MMPattern[]): pl is PatternList =>
+  pl.length >= 1
+const isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1
+
+const customInspect = Symbol.for('nodejs.util.inspect.custom')
+
+/**
+ * An immutable-ish view on an array of glob parts and their parsed
+ * results
+ */
+export class Pattern {
+  readonly #patternList: PatternList
+  readonly #globList: GlobList
+  readonly #index: number
+  readonly length: number
+  readonly #platform: NodeJS.Platform
+  #rest?: Pattern | null
+  #globString?: string
+  #isDrive?: boolean
+  #isUNC?: boolean
+  #isAbsolute?: boolean
+  #followGlobstar: boolean = true
+
+  constructor(
+    patternList: MMPattern[],
+    globList: string[],
+    index: number,
+    platform: NodeJS.Platform,
+  ) {
+    if (!isPatternList(patternList)) {
+      throw new TypeError('empty pattern list')
+    }
+    if (!isGlobList(globList)) {
+      throw new TypeError('empty glob list')
+    }
+    if (globList.length !== patternList.length) {
+      throw new TypeError('mismatched pattern list and glob list lengths')
+    }
+    this.length = patternList.length
+    if (index < 0 || index >= this.length) {
+      throw new TypeError('index out of range')
+    }
+    this.#patternList = patternList
+    this.#globList = globList
+    this.#index = index
+    this.#platform = platform
+
+    // normalize root entries of absolute patterns on initial creation.
+    if (this.#index === 0) {
+      // c: => ['c:/']
+      // C:/ => ['C:/']
+      // C:/x => ['C:/', 'x']
+      // //host/share => ['//host/share/']
+      // //host/share/ => ['//host/share/']
+      // //host/share/x => ['//host/share/', 'x']
+      // //?/UNC/host/share/x => ['//?/UNC/host/share/', 'x']
+      // /etc => ['/', 'etc']
+      // / => ['/']
+      if (this.isUNC()) {
+        // '' / '' / 'host' / 'share', or
+        // '' / '' / '?' / 'UNC' / 'host' / 'share'
+        const n = this.#isLongUNC() ? 6 : 4
+        const proot = this.#patternList.slice(0, n)
+        const groot = this.#globList.slice(0, n)
+        const prest = this.#patternList.slice(n)
+        const grest = this.#globList.slice(n)
+        if (prest[0] === '') {
+          // ends in /
+          prest.shift()
+          grest.shift()
+        }
+        const p = [...proot, ''].join('/')
+        const g = [...groot, ''].join('/')
+        this.#patternList = [p, ...prest]
+        this.#globList = [g, ...grest]
+        this.length = this.#patternList.length
+      } else if (this.isDrive() || this.isAbsolute()) {
+        const [p1, ...prest] = this.#patternList
+        const [g1, ...grest] = this.#globList
+        if (prest[0] === '') {
+          // ends in /
+          prest.shift()
+          grest.shift()
+        }
+        const p = `${p1 as string}/`
+        const g = `${g1}/`
+        this.#patternList = [p, ...prest]
+        this.#globList = [g, ...grest]
+        this.length = this.#patternList.length
+      }
+    }
+  }
+
+  [customInspect]() {
+    return `Pattern <${this.#globList.slice(this.#index).join('/')}>`
+  }
+
+  /**
+   * The first entry in the parsed list of patterns
+   */
+  pattern(): MMPattern {
+    return this.#patternList[this.#index] as MMPattern
+  }
+
+  /**
+   * true of if pattern() returns a string
+   */
+  isString(): boolean {
+    return typeof this.#patternList[this.#index] === 'string'
+  }
+  /**
+   * true of if pattern() returns GLOBSTAR
+   */
+  isGlobstar(): boolean {
+    return this.#patternList[this.#index] === GLOBSTAR
+  }
+  /**
+   * true if pattern() returns a Matcher, for a portion with magic
+   */
+  isMatcher(): boolean {
+    return typeof this.#patternList[this.#index] === 'object'
+  }
+
+  /**
+   * The /-joined set of glob parts that make up this pattern
+   */
+  globString(): string {
+    return (this.#globString =
+      this.#globString ||
+      (this.#index === 0 ?
+        this.isAbsolute() ?
+          this.#globList[0] + this.#globList.slice(1).join('/')
+        : this.#globList.join('/')
+      : this.#globList.slice(this.#index).join('/')))
+  }
+
+  /**
+   * true if there are more pattern parts after this one
+   */
+  hasMore(): boolean {
+    return this.length > this.#index + 1
+  }
+
+  /**
+   * The rest of the pattern after this part, or null if this is the end
+   */
+  rest(): Pattern | null {
+    if (this.#rest !== undefined) return this.#rest
+    if (!this.hasMore()) return (this.#rest = null)
+    this.#rest = new Pattern(
+      this.#patternList,
+      this.#globList,
+      this.#index + 1,
+      this.#platform,
+    )
+    this.#rest.#isAbsolute = this.#isAbsolute
+    this.#rest.#isUNC = this.#isUNC
+    this.#rest.#isDrive = this.#isDrive
+    return this.#rest
+  }
+
+  // the root is //?/UNC/host/share, the same as //host/share
+  #isLongUNC(): boolean {
+    const pl = this.#patternList
+    return (
+      pl[2] === '?' && typeof pl[3] === 'string' && /^unc$/i.test(pl[3])
+    )
+  }
+
+  /**
+   * true if the pattern represents a //unc/path/ on windows
+   */
+  isUNC(): boolean {
+    const pl = this.#patternList
+    // the host and share, after //?/UNC/ in a long UNC path
+    const h = this.#isLongUNC() ? 4 : 2
+    return this.#isUNC !== undefined ?
+        this.#isUNC
+      : (this.#isUNC =
+          this.#platform === 'win32' &&
+          this.#index === 0 &&
+          pl[0] === '' &&
+          pl[1] === '' &&
+          typeof pl[h] === 'string' &&
+          !!pl[h] &&
+          typeof pl[h + 1] === 'string' &&
+          !!pl[h + 1])
+  }
+
+  // pattern like C:/...
+  // split = ['C:', ...]
+  // XXX: would be nice to handle patterns like `c:*` to test the cwd
+  // in c: for *, but I don't know of a way to even figure out what that
+  // cwd is without actually chdir'ing into it?
+  /**
+   * True if the pattern starts with a drive letter on Windows
+   */
+  isDrive(): boolean {
+    const pl = this.#patternList
+    return this.#isDrive !== undefined ?
+        this.#isDrive
+      : (this.#isDrive =
+          this.#platform === 'win32' &&
+          this.#index === 0 &&
+          this.length > 1 &&
+          typeof pl[0] === 'string' &&
+          /^[a-z]:$/i.test(pl[0]))
+  }
+
+  // pattern = '/' or '/...' or '/x/...'
+  // split = ['', ''] or ['', ...] or ['', 'x', ...]
+  // Drive and UNC both considered absolute on windows
+  /**
+   * True if the pattern is rooted on an absolute path
+   */
+  isAbsolute(): boolean {
+    const pl = this.#patternList
+    return this.#isAbsolute !== undefined ?
+        this.#isAbsolute
+      : (this.#isAbsolute =
+          (pl[0] === '' && pl.length > 1) ||
+          this.isDrive() ||
+          this.isUNC())
+  }
+
+  /**
+   * consume the root of the pattern, and return it
+   */
+  root(): string {
+    const p = this.#patternList[0]
+    return (
+        typeof p === 'string' && this.isAbsolute() && this.#index === 0
+      ) ?
+        p
+      : ''
+  }
+
+  /**
+   * Check to see if the current globstar pattern is allowed to follow
+   * a symbolic link.
+   */
+  checkFollowGlobstar(): boolean {
+    return !(
+      this.#index === 0 ||
+      !this.isGlobstar() ||
+      !this.#followGlobstar
+    )
+  }
+
+  /**
+   * Mark that the current globstar pattern is following a symbolic link
+   */
+  markFollowGlobstar(): boolean {
+    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
+      return false
+    this.#followGlobstar = false
+    return true
+  }
+}
diff --git a/mac/patchers/desktop/node_modules/glob/src/processor.ts b/mac/patchers/desktop/node_modules/glob/src/processor.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d6f491896cb258139cf56d1b25257d42d7012f9c
--- /dev/null
+++ b/mac/patchers/desktop/node_modules/glob/src/processor.ts
@@ -0,0 +1,333 @@
+// synchronous utility for filtering entries and calculating subwalks
+
+import { GLOBSTAR } from 'minimatch'
+import type { Path } from 'path-scurry'
+import type { MMMatcher, MMPattern, Pattern } from './pattern.js'
+import type { GlobWalkerOpts } from './walker.js'
+
+/**
+ * A cache of which patterns have been processed for a given Path, in
+ * this walk step and the steps that led to it.
+ *
+ * A step only adds to it before it makes the caches for the next
+ * steps, so a copy can look up the chain of caches before it, in
+ * place of copying their entries. A pattern for a path that a cache
+ * up the chain has already seen is added to that cache's set, so that
+ * the other steps that share it see it too. Paths are keyed by their
+ * full path, because path-scurry can make a new Path object for the
+ * same path once its cache of children is full.
+ */
+export class HasWalkedCache {
+  parent?: HasWalkedCache
+  store?: Map>
+  constructor(parent?: HasWalkedCache) {
+    this.parent = parent
+  }
+  copy() {
+    return new HasWalkedCache(this)
+  }
+  // the set for the path in this cache, or the closest one before it
+  #find(fullpath: string): Set | undefined {
+    const set = this.store?.get(fullpath)
+    return set || !this.parent ? set : this.parent.#find(fullpath)
+  }
+
+  hasWalked(target: Path, pattern: Pattern) {
+    return !!this.#find(target.fullpath())?.has(pattern.globString())
+  }
+  storeWalked(target: Path, pattern: Pattern) {
+    const fullpath = target.fullpath()
+    const cached = this.#find(fullpath)
+    if (cached) cached.add(pattern.globString())
+    else
+      (this.store ??= new Map()).set(
+        fullpath,
+        new Set([pattern.globString()]),
+      )
+  }
+}
+
+/**
+ * A record of which paths have been matched in a given walk step,
+ * and whether they only are considered a match if they are a directory,
+ * and whether their absolute or relative path should be returned.
+ * The store maps each path to {@link MatchRecord.ABSOLUTE} and
+ * {@link MatchRecord.IF_DIR} flags.
+ */
+export class MatchRecord {
+  static readonly ABSOLUTE = 2
+  static readonly IF_DIR = 1
+  store: Map = new Map()
+  add(target: Path, absolute: boolean, ifDir: boolean) {
+    const n =
+      (absolute ? MatchRecord.ABSOLUTE : 0) |
+      (ifDir ? MatchRecord.IF_DIR : 0)
+    const current = this.store.get(target)
+    this.store.set(target, current === undefined ? n : n & current)
+  }
+}
+
+/**
+ * A collection of patterns that must be processed in a subsequent step
+ * for a given path.
+ */
+export class SubWalks {
+  store: Map = new Map()
+  add(target: Path, pattern: Pattern) {
+    if (!target.canReaddir()) {
+      return
+    }
+    const subs = this.store.get(target)
+    if (subs) {
+      if (!subs.find(p => p.globString() === pattern.globString())) {
+        subs.push(pattern)
+      }
+    } else this.store.set(target, [pattern])
+  }
+  get(target: Path): Pattern[] {
+    const subs = this.store.get(target)
+    /* c8 ignore start */
+    if (!subs) {
+      throw new Error('attempting to walk unknown path')
+    }
+    /* c8 ignore stop */
+    return subs
+  }
+  entries(): [Path, Pattern[]][] {
+    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])
+  }
+  keys(): Path[] {
+    return [...this.store.keys()].filter(t => t.canReaddir())
+  }
+}
+
+/**
+ * The class that processes patterns for a given path.
+ *
+ * Handles child entry filtering, and determining whether a path's
+ * directory contents must be read.
+ */
+export class Processor {
+  hasWalkedCache: HasWalkedCache
+  matches = new MatchRecord()
+  subwalks = new SubWalks()
+  patterns?: Pattern[]
+  follow: boolean
+  dot: boolean
+  opts: GlobWalkerOpts
+
+  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {
+    this.opts = opts
+    this.follow = !!opts.follow
+    this.dot = !!opts.dot
+    this.hasWalkedCache =
+      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()
+  }
+
+  processPatterns(target: Path, patterns: Pattern[]) {
+    this.patterns = patterns
+    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])
+
+    // map of paths to the magic-starting subwalks they need to walk
+    // first item in patterns is the filter
+
+    for (let [t, pattern] of processingSet) {
+      this.hasWalkedCache.storeWalked(t, pattern)
+
+      const root = pattern.root()
+      const absolute = pattern.isAbsolute() && this.opts.absolute !== false
+
+      // start absolute patterns at root
+      if (root) {
+        t = t.resolve(
+          root === '/' && this.opts.root !== undefined ?
+            this.opts.root
+          : root,
+        )
+        const rest = pattern.rest()
+        if (!rest) {
+          this.matches.add(t, true, false)
+          continue
+        } else {
+          pattern = rest
+        }
+      }
+
+      if (t.isENOENT()) continue
+
+      let p: MMPattern
+      let rest: Pattern | null
+      let changed = false
+      while (
+        typeof (p = pattern.pattern()) === 'string' &&
+        (rest = pattern.rest())
+      ) {
+        const c = t.resolve(p)
+        t = c
+        pattern = rest
+        changed = true
+      }
+      p = pattern.pattern()
+      rest = pattern.rest()
+      if (changed) {
+        if (this.hasWalkedCache.hasWalked(t, pattern)) continue
+        this.hasWalkedCache.storeWalked(t, pattern)
+      }
+
+      // now we have either a final string for a known entry,
+      // more strings for an unknown entry,
+      // or a pattern starting with magic, mounted on t.
+      if (typeof p === 'string') {
+        // must not be final entry, otherwise we would have
+        // concatenated it earlier.
+        const ifDir = p === '..' || p === '' || p === '.'
+        this.matches.add(t.resolve(p), absolute, ifDir)
+        continue
+      } else if (p === GLOBSTAR) {
+        // if no rest, match and subwalk pattern
+        // if rest, process rest and subwalk pattern
+        // if it's a symlink, but we didn't get here by way of a
+        // globstar match (meaning it's the first time THIS globstar
+        // has traversed a symlink), then we follow it. Otherwise, stop.
+        if (
+          !t.isSymbolicLink() ||
+          this.follow ||
+          pattern.checkFollowGlobstar()
+        ) {
+          this.subwalks.add(t, pattern)
+        }
+        const rp = rest?.pattern()
+        const rrest = rest?.rest()
+        if (!rest || ((rp === '' || rp === '.') && !rrest)) {
+          // only HAS to be a dir if it ends in **/ or **/.
+          // but ending in ** will match files as well.
+          this.matches.add(t, absolute, rp === '' || rp === '.')
+        } else {
+          if (rp === '..') {
+            // this would mean you're matching **/.. at the fs root,
+            // and no thanks, I'm not gonna test that specific case.
+            /* c8 ignore start */
+            const tp = t.parent || t
+            /* c8 ignore stop */
+            if (!rrest) this.matches.add(tp, absolute, true)
+            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
+              this.subwalks.add(tp, rrest)
+            }
+          }
+        }
+      } else if (typeof p === 'object') {
+        this.subwalks.add(t, pattern)
+      }
+    }
+
+    return this
+  }
+
+  subwalkTargets(): Path[] {
+    return this.subwalks.keys()
+  }
+
+  child() {
+    return new Processor(this.opts, this.hasWalkedCache)
+  }
+
+  // return a new Processor containing the subwalks for each
+  // child entry, and a set of matches, and
+  // a hasWalkedCache that's a copy of this one
+  // then we're going to call
+  filterEntries(parent: Path, entries: Path[]): Processor {
+    const patterns = this.subwalks.get(parent)
+    // put matches and entry walks into the results processor
+    const results = this.child()
+    for (const e of entries) {
+      for (const pattern of patterns) {
+        const absolute = pattern.isAbsolute()
+        const p = pattern.pattern()
+        const rest = pattern.rest()
+        if (p === GLOBSTAR) {
+          results.testGlobstar(e, pattern, rest, absolute)
+        } else if (typeof p === 'object') {
+          results.testMatcher(e, p, rest, absolute)
+        } else {
+          results.testString(e, p, rest, absolute)
+        }
+      }
+    }
+    return results
+  }
+
+  testGlobstar(
+    e: Path,
+    pattern: Pattern,
+    rest: Pattern | null,
+    absolute: boolean,
+  ) {
+    if (this.dot || !e.name.startsWith('.')) {
+      if (!pattern.hasMore()) {
+        this.matches.add(e, absolute, false)
+      }
+      if (e.canReaddir()) {
+        // if we're in follow mode or it's not a symlink, just keep
+        // testing the same pattern. If there's more after the globstar,
+        // then this symlink consumes the globstar. If not, then we can
+        // follow at most ONE symlink along the way, so we mark it, which
+        // also checks to ensure that it wasn't already marked.
+        if (this.follow || !e.isSymbolicLink()) {
+          this.subwalks.add(e, pattern)
+        } else if (e.isSymbolicLink()) {
+          if (rest && pattern.checkFollowGlobstar()) {
+            this.subwalks.add(e, rest)
+          } else if (pattern.markFollowGlobstar()) {
+            this.subwalks.add(e, pattern)
+          }
+        }
+      }
+    }
+    // if the NEXT thing matches this entry, then also add
+    // the rest.
+    if (rest) {
+      const rp = rest.pattern()
+      if (
+        typeof rp === 'string' &&
+        // dots and empty were handled already
+        rp !== '..' &&
+        rp !== '' &&
+        rp !== '.'
+      ) {
+        this.testString(e, rp, rest.rest(), absolute)
+      } else if (rp === '..') {
+        /* c8 ignore start */
+        const ep = e.parent || e
+        /* c8 ignore stop */
+        this.subwalks.add(ep, rest)
+      } else if (typeof rp === 'object') {
+        this.testMatcher(e, rp, rest.rest(), absolute)
+      }
+    }
+  }
+
+  testMatcher(
+    e: Path,
+    p: MMMatcher,
+    rest: Pattern | null,
+    absolute: boolean,
+  ) {
+    // an entry name is one path portion, with no `/`
+    if (!p.testUnchecked(e.name)) return
+    if (!rest) {
+      this.matches.add(e, absolute, false)
+    } else {
+      this.subwalks.add(e, rest)
+    }
+  }
+
+  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {
+    // should never happen?
+    if (!e.isNamed(p)) return
+    if (!rest) {
+      this.matches.add(e, absolute, false)
+    } else {
+      this.subwalks.add(e, rest)
+    }
+  }
+}
diff --git a/mac/patchers/desktop/node_modules/glob/src/walker.ts b/mac/patchers/desktop/node_modules/glob/src/walker.ts
new file mode 100644
index 0000000000000000000000000000000000000000..205263d161760be16bbdb1c3f17d106923638c1d
--- /dev/null
+++ b/mac/patchers/desktop/node_modules/glob/src/walker.ts
@@ -0,0 +1,524 @@
+/**
+ * Single-use utility classes to provide functionality to the {@link Glob}
+ * methods.
+ *
+ * @module
+ */
+import { Minipass } from 'minipass'
+import type { Form } from 'minimatch'
+import type { Path } from 'path-scurry'
+import type { IgnoreLike } from './ignore.js'
+import { Ignore } from './ignore.js'
+
+// XXX can we somehow make it so that it NEVER processes a given path more than
+// once, enough that the match set tracking is no longer needed?  that'd speed
+// things up a lot.  Or maybe bring back nounique, and skip it in that case?
+
+// a single minimatch set entry with 1 or more parts
+import type { Pattern } from './pattern.js'
+import { MatchRecord, Processor } from './processor.js'
+
+const { ABSOLUTE, IF_DIR } = MatchRecord
+
+export interface GlobWalkerOpts {
+  absolute?: boolean
+  allowWindowsEscape?: boolean
+  braceExpandMax?: number
+  cwd?: string | URL
+  dot?: boolean
+  dotRelative?: boolean
+  follow?: boolean
+  ignore?: string | string[] | IgnoreLike | ReadonlyArray
+  mark?: boolean
+  matchBase?: boolean
+  // Note: maxDepth here means "maximum actual Path.depth()",
+  // not "maximum depth beyond cwd"
+  maxDepth?: number
+  nobrace?: boolean
+  nocase?: boolean
+  nodir?: boolean
+  noext?: boolean
+  noglobstar?: boolean
+  normalize?: boolean | Form
+  platform?: NodeJS.Platform
+  posix?: boolean
+  realpath?: boolean
+  root?: string
+  stat?: boolean
+  signal?: AbortSignal
+  windowsPathsNoEscape?: boolean
+  withFileTypes?: boolean
+  includeChildMatches?: boolean
+}
+
+export type GWOFileTypesTrue = GlobWalkerOpts & {
+  withFileTypes: true
+}
+export type GWOFileTypesFalse = GlobWalkerOpts & {
+  withFileTypes: false
+}
+export type GWOFileTypesUnset = GlobWalkerOpts & {
+  withFileTypes?: undefined
+}
+
+export type Result =
+  O extends GWOFileTypesTrue ? Path
+  : O extends GWOFileTypesFalse ? string
+  : O extends GWOFileTypesUnset ? string
+  : Path | string
+
+export type Matches =
+  O extends GWOFileTypesTrue ? Path[]
+  : O extends GWOFileTypesFalse ? string[]
+  : O extends GWOFileTypesUnset ? string[]
+  : (Path | string)[]
+
+export type MatchStream = Minipass<
+  Result,
+  Result
+>
+
+const makeIgnore = (
+  ignore: string | string[] | IgnoreLike | ReadonlyArray,
+  opts: GlobWalkerOpts,
+  cwd: Path,
+): IgnoreLike =>
+  typeof ignore === 'string' ? new Ignore([ignore], opts, cwd)
+  : Array.isArray(ignore) ? new Ignore(ignore, opts, cwd)
+  : (ignore as IgnoreLike)
+
+/**
+ * basic walking utilities that all the glob walker types use
+ */
+export abstract class GlobUtil {
+  path: Path
+  patterns: Pattern[]
+  opts: O
+  seen: Set = new Set()
+  paused: boolean = false
+  aborted: boolean = false
+  #onResume: (() => unknown)[] = []
+  #ignore?: IgnoreLike
+  #sep: '\\' | '/'
+  signal?: AbortSignal
+  maxDepth: number
+  includeChildMatches: boolean
+
+  constructor(patterns: Pattern[], path: Path, opts: O)
+  constructor(patterns: Pattern[], path: Path, opts: O) {
+    this.patterns = patterns
+    this.path = path
+    this.opts = opts
+    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/'
+    this.includeChildMatches = opts.includeChildMatches !== false
+    if (opts.ignore || !this.includeChildMatches) {
+      this.#ignore = makeIgnore(opts.ignore ?? [], opts, path)
+      if (
+        !this.includeChildMatches &&
+        typeof this.#ignore.add !== 'function'
+      ) {
+        const m = 'cannot ignore child matches, ignore lacks add() method.'
+        throw new Error(m)
+      }
+    }
+    // ignore, always set with maxDepth, but it's optional on the
+    // GlobOptions type
+    /* c8 ignore start */
+    this.maxDepth = opts.maxDepth || Infinity
+    /* c8 ignore stop */
+    if (opts.signal) {
+      this.signal = opts.signal
+      this.signal.addEventListener('abort', () => {
+        this.#onResume.length = 0
+      })
+    }
+  }
+
+  #ignored(path: Path): boolean {
+    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)
+  }
+  #childrenIgnored(path: Path): boolean {
+    return !!this.#ignore?.childrenIgnored?.(path)
+  }
+
+  // backpressure mechanism
+  pause() {
+    this.paused = true
+  }
+  resume() {
+    /* c8 ignore start */
+    if (this.signal?.aborted) return
+    /* c8 ignore stop */
+    this.paused = false
+    let fn: (() => unknown) | undefined = undefined
+    while (!this.paused && (fn = this.#onResume.shift())) {
+      fn()
+    }
+  }
+  onResume(fn: () => unknown) {
+    /* c8 ignore start */
+    if (!this.paused) {
+      fn()
+    } else {
+      /* c8 ignore stop */
+      this.#onResume.push(fn)
+    }
+  }
+
+  // do the requisite realpath/stat checking, and return the path
+  // to add or undefined to filter it out.
+  async matchCheck(
+    inPath: Path,
+    ifDir: boolean,
+  ): Promise {
+    if (ifDir && this.opts.nodir) return undefined
+    let rpc: Path | undefined
+    let e: Path
+    if (this.opts.realpath) {
+      rpc = inPath.realpathCached() || (await inPath.realpath())
+      if (!rpc) return undefined
+      e = rpc
+    } else {
+      e = inPath
+    }
+    const needStat = e.isUnknown() || this.opts.stat
+    const s = needStat ? await e.lstat() : e
+    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
+      const target = await s.realpath()
+      /* c8 ignore start */
+      if (target && (target.isUnknown() || this.opts.stat)) {
+        await target.lstat()
+      }
+      /* c8 ignore stop */
+    }
+    return this.matchCheckTest(s, ifDir)
+  }
+
+  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {
+    return (
+        e &&
+          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&
+          (!ifDir || e.canReaddir()) &&
+          (!this.opts.nodir || !e.isDirectory()) &&
+          (!this.opts.nodir ||
+            !this.opts.follow ||
+            !e.isSymbolicLink() ||
+            !e.realpathCached()?.isDirectory()) &&
+          !this.#ignored(e)
+      ) ?
+        e
+      : undefined
+  }
+
+  matchCheckSync(inPath: Path, ifDir: boolean): Path | undefined {
+    if (ifDir && this.opts.nodir) return undefined
+    let rpc: Path | undefined
+    let e: Path
+    if (this.opts.realpath) {
+      rpc = inPath.realpathCached() || inPath.realpathSync()
+      if (!rpc) return undefined
+      e = rpc
+    } else {
+      e = inPath
+    }
+    const needStat = e.isUnknown() || this.opts.stat
+    const s = needStat ? e.lstatSync() : e
+    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
+      const target = s.realpathSync()
+      if (target && (target?.isUnknown() || this.opts.stat)) {
+        target.lstatSync()
+      }
+    }
+    return this.matchCheckTest(s, ifDir)
+  }
+
+  abstract matchEmit(p: Result): void
+  abstract matchEmit(p: string | Path): void
+
+  matchFinish(e: Path, absolute: boolean) {
+    if (this.#ignored(e)) return
+    this.#matchEmitChecked(e, absolute)
+  }
+
+  // emit a match that is known to not be seen or ignored yet
+  #matchEmitChecked(e: Path, absolute: boolean) {
+    // we know we have an ignore if this is false, but TS doesn't
+    if (!this.includeChildMatches && this.#ignore?.add) {
+      const ign = `${e.relativePosix()}/**`
+      this.#ignore.add(ign)
+    }
+    const abs =
+      this.opts.absolute === undefined ? absolute : this.opts.absolute
+    this.seen.add(e)
+    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''
+    // ok, we have what we need!
+    if (this.opts.withFileTypes) {
+      this.matchEmit(e)
+    } else if (abs) {
+      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()
+      this.matchEmit(abs + mark)
+    } else {
+      const rel = this.opts.posix ? e.relativePosix() : e.relative()
+      const pre =
+        this.opts.dotRelative && !rel.startsWith(`..${this.#sep}`) ?
+          `.${this.#sep}`
+        : ''
+      this.matchEmit(!rel ? `.${mark}` : pre + rel + mark)
+    }
+  }
+
+  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {
+    const p = await this.matchCheck(e, ifDir)
+    if (p) this.matchFinish(p, absolute)
+  }
+
+  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {
+    // matchCheckSync just checked that it is not seen or ignored, and
+    // nothing can have changed since
+    const p = this.matchCheckSync(e, ifDir)
+    if (p) this.#matchEmitChecked(p, absolute)
+  }
+
+  walkCB(target: Path, patterns: Pattern[], cb: () => unknown) {
+    /* c8 ignore start */
+    if (this.signal?.aborted) return cb()
+    /* c8 ignore stop */
+    this.walkCB2(target, patterns, new Processor(this.opts), cb)
+  }
+
+  walkCB2(
+    target: Path,
+    patterns: Pattern[],
+    processor: Processor,
+    cb: () => unknown,
+  ) {
+    if (this.#childrenIgnored(target)) return cb()
+    if (this.signal?.aborted) return cb()
+    if (this.paused) {
+      this.onResume(() => this.walkCB2(target, patterns, processor, cb))
+      return
+    }
+    processor.processPatterns(target, patterns)
+
+    // done processing.  all of the above is sync, can be abstracted out.
+    // subwalks is a map of paths to the entry filters they need
+    // matches is a map of paths to [absolute, ifDir] tuples.
+    let tasks = 1
+    const next = () => {
+      if (--tasks === 0) cb()
+    }
+
+    for (const [m, n] of processor.matches.store) {
+      if (this.#ignored(m)) continue
+      tasks++
+      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>
+        next(),
+      )
+    }
+
+    for (const t of processor.subwalkTargets()) {
+      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
+        continue
+      }
+      tasks++
+      const childrenCached = t.readdirCached()
+      if (t.calledReaddir())
+        this.walkCB3(t, childrenCached, processor, next)
+      else {
+        t.readdirCB(
+          (_, entries) => this.walkCB3(t, entries, processor, next),
+          true,
+        )
+      }
+    }
+
+    next()
+  }
+
+  walkCB3(
+    target: Path,
+    entries: Path[],
+    processorx: Processor,
+    cb: () => unknown,
+  ) {
+    const proc = processorx.filterEntries(target, entries)
+
+    let tasks = 1
+    const next = () => {
+      if (--tasks === 0) cb()
+    }
+
+    for (const [m, n] of proc.matches.store) {
+      if (this.#ignored(m)) continue
+      tasks++
+      void this.match(m, !!(n & ABSOLUTE), !!(n & IF_DIR)).then(() =>
+        next(),
+      )
+    }
+    for (const [target, patterns] of proc.subwalks.entries()) {
+      tasks++
+      this.walkCB2(target, patterns, proc.child(), next)
+    }
+
+    next()
+  }
+
+  walkCBSync(target: Path, patterns: Pattern[], cb: () => unknown) {
+    /* c8 ignore start */
+    if (this.signal?.aborted) return cb()
+    /* c8 ignore stop */
+    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)
+  }
+
+  walkCB2Sync(
+    target: Path,
+    patterns: Pattern[],
+    processor: Processor,
+    cb: () => unknown,
+  ) {
+    if (this.#childrenIgnored(target)) return cb()
+    if (this.signal?.aborted) return cb()
+    if (this.paused) {
+      this.onResume(() =>
+        this.walkCB2Sync(target, patterns, processor, cb),
+      )
+      return
+    }
+    processor.processPatterns(target, patterns)
+
+    // done processing.  all of the above is sync, can be abstracted out.
+    // subwalks is a map of paths to the entry filters they need
+    // matches is a map of paths to [absolute, ifDir] tuples.
+    let tasks = 1
+    const next = () => {
+      if (--tasks === 0) cb()
+    }
+
+    for (const [m, n] of processor.matches.store) {
+      if (this.#ignored(m)) continue
+      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))
+    }
+
+    for (const t of processor.subwalkTargets()) {
+      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
+        continue
+      }
+      tasks++
+      const children = t.readdirSync()
+      this.walkCB3Sync(t, children, processor, next)
+    }
+
+    next()
+  }
+
+  walkCB3Sync(
+    target: Path,
+    entries: Path[],
+    processor: Processor,
+    cb: () => unknown,
+  ) {
+    const proc = processor.filterEntries(target, entries)
+
+    let tasks = 1
+    const next = () => {
+      if (--tasks === 0) cb()
+    }
+
+    for (const [m, n] of proc.matches.store) {
+      if (this.#ignored(m)) continue
+      this.matchSync(m, !!(n & ABSOLUTE), !!(n & IF_DIR))
+    }
+    for (const [target, patterns] of proc.subwalks.entries()) {
+      tasks++
+      this.walkCB2Sync(target, patterns, proc.child(), next)
+    }
+
+    next()
+  }
+}
+
+export class GlobWalker<
+  O extends GlobWalkerOpts = GlobWalkerOpts,
+> extends GlobUtil {
+  // each Path is only emitted once (see GlobUtil.seen), so the results
+  // do not need to be deduped
+  matches: Result[] = []
+
+  constructor(patterns: Pattern[], path: Path, opts: O) {
+    super(patterns, path, opts)
+  }
+
+  matchEmit(e: Result): void {
+    this.matches.push(e)
+  }
+
+  async walk(): Promise[]> {
+    if (this.signal?.aborted) throw this.signal.reason
+    if (this.path.isUnknown()) {
+      await this.path.lstat()
+    }
+    await new Promise((res, rej) => {
+      this.walkCB(this.path, this.patterns, () => {
+        if (this.signal?.aborted) {
+          rej(this.signal.reason)
+        } else {
+          res(this.matches)
+        }
+      })
+    })
+    return this.matches
+  }
+
+  walkSync(): Result[] {
+    if (this.signal?.aborted) throw this.signal.reason
+    if (this.path.isUnknown()) {
+      this.path.lstatSync()
+    }
+    // nothing for the callback to do, because this never pauses
+    this.walkCBSync(this.path, this.patterns, () => {
+      if (this.signal?.aborted) throw this.signal.reason
+    })
+    return this.matches
+  }
+}
+
+export class GlobStream<
+  O extends GlobWalkerOpts = GlobWalkerOpts,
+> extends GlobUtil {
+  results: Minipass, Result>
+
+  constructor(patterns: Pattern[], path: Path, opts: O) {
+    super(patterns, path, opts)
+    this.results = new Minipass, Result>({
+      signal: this.signal,
+      objectMode: true,
+    })
+    this.results.on('drain', () => this.resume())
+    this.results.on('resume', () => this.resume())
+  }
+
+  matchEmit(e: Result): void {
+    this.results.write(e)
+    if (!this.results.flowing) this.pause()
+  }
+
+  stream(): MatchStream {
+    const target = this.path
+    if (target.isUnknown()) {
+      void target.lstat().then(() => {
+        this.walkCB(target, this.patterns, () => this.results.end())
+      })
+    } else {
+      this.walkCB(target, this.patterns, () => this.results.end())
+    }
+    return this.results
+  }
+
+  streamSync(): MatchStream {
+    if (this.path.isUnknown()) {
+      this.path.lstatSync()
+    }
+    this.walkCBSync(this.path, this.patterns, () => this.results.end())
+    return this.results
+  }
+}
diff --git a/mac/patchers/desktop/node_modules/minimatch/README.md b/mac/patchers/desktop/node_modules/minimatch/README.md
index 1a068fab2a0fb246162b55c9aec983019282b37a..dcce44e97da4346cc765d28a2fc4866736ac6f30 100644
--- a/mac/patchers/desktop/node_modules/minimatch/README.md
+++ b/mac/patchers/desktop/node_modules/minimatch/README.md
@@ -1,60 +1,62 @@
 # minimatch
 
-A minimal matching utility.
+A glob matching utility.
 
-This is the matching library used internally by npm.
+This is the matching library used internally by
+[node-glob](https://npm.im/node-glob).
 
-It works by converting glob expressions into JavaScript `RegExp`
-objects.
+It works by splitting glob expressions on `/`, and testing each
+path portion with a `Matcher` from
+[@isaacs/nonrecursive-glob-match](http://npm.im/@isaacs/nonrecursive-glob-match).
 
-## Important Security Consideration!
+## Why Not Regular Expressions?
 
-> [!WARNING]  
-> This library uses JavaScript regular expressions. Please read
-> the following warning carefully, and be thoughtful about what
-> you provide to this library in production systems.
+Regular Expressions are very powerful, and for many applications,
+extremely fast.
 
-_Any_ library in JavaScript that deals with matching string
-patterns using regular expressions will be subject to
+However, in JavaScript, they are subject to
 [ReDoS](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS)
-if the pattern is generated using untrusted input.
+in certain cases. Libraries that assemble Regular Expressions
+from arbitrary input are thus vulnerable to patterns that cause
+pathological behavior. For example, patterns like
+`a*a*a*a*a*a*a*a*a*a*a` when matched against a string like
+`'a'.repeat(50) + 'b'` would have to repeatedly backtrack through
+every failure.
+
+Most other glob matchers in JavaScript (including versions up
+through v10 of this library) convert the glob pattern to Regular
+Expressions, and then use that to test the string. This is fine
+for trusted input, but can fall over badly in cases that cause
+recursive backtracking.
+
+## Important Security Consideration!
 
-Efforts have been made to mitigate risk as much as is feasible in
-such a library, providing maximum recursion depths and so forth,
-but these measures can only ultimately protect against accidents,
-not malice. A dedicated attacker can _always_ find patterns that
-cannot be defended against by a bash-compatible glob pattern
-matching system that uses JavaScript regular expressions.
+Though this library is _not_ vulnerable to ReDOS, _any_ library
+that performs pattern matching based on arbitrary input will
+potentially have edge cases where it performs suboptimally.
 
 To be extremely clear:
 
 > [!WARNING]  
 > **If you create a system where you take user input, and use
-> that input as the source of a Regular Expression pattern, in
-> this or any extant glob matcher in JavaScript, you will be
-> pwned.**
+> that input as the source of a pattern matcher, in this or any
+> extant glob matcher in JavaScript, you may be pwned.**
 
-A future version of this library _may_ use a different matching
-algorithm which does not exhibit backtracking problems. If and
-when that happens, it will likely be a sweeping change, and those
-improvements will **not** be backported to legacy versions.
-
-In the near term, it is not reasonable to continue to play
-whack-a-mole with security advisories, and so any future ReDoS
-reports will be considered "working as intended", and resolved
-entirely by this warning.
+The pattern matching library that Minimatch uses in v11 and above
+will not be backported to earlier versions. It is a much too deep
+of a change to do so.
 
 ## Usage
 
-```js
+```ts
 // hybrid module, load with require() or import
 import { minimatch } from 'minimatch'
 // or:
-const { minimatch } = require('minimatch')
+// const { minimatch } = require('minimatch')
 
 minimatch('bar.foo', '*.foo') // true!
 minimatch('bar.foo', '*.bar') // false!
-minimatch('bar.foo', '*.+(bar|foo)', { debug: true }) // true, and noisy!
+minimatch('bar.foo', '*.+(bar|foo)') // true!
 ```
 
 ## Features
@@ -112,6 +114,14 @@ On Windows, UNC paths like `//?/c:/...` or
   present when the drive letters are a case-insensitive match to
   one another. The remaining portions of the path/pattern are
   compared case sensitively, unless `nocase:true` is set.
+- The host and share of a pattern starting with
+  `////...` are compared case-insensitively with
+  those of the file path, if neither has magic. For example,
+  `//host/share/*` matches `//HOST/SHARE/x`.
+- Patterns starting with `//?/UNC///...` will match
+  file paths starting with `////...`, and vice
+  versa, the same as `//?/:`. The `?` is not a
+  wildcard character.
 
 Note that specifying a UNC path using `\` characters as path
 separators is always allowed in the file path argument, but only
@@ -123,15 +133,15 @@ is set in the options.
 Create a minimatch object by instantiating the `minimatch.Minimatch` class.
 
 ```javascript
-var Minimatch = require('minimatch').Minimatch
-var mm = new Minimatch(pattern, options)
+import { Minimatch } from 'minimatch'
+const mm = new Minimatch(pattern, options)
 ```
 
 ### Properties
 
 - `pattern` The original pattern the minimatch object represents.
 - `options` The options supplied to the constructor.
-- `set` A 2-dimensional array of regexp or string expressions.
+- `set` A 2-dimensional array of `Matcher` or string expressions.
   Each row in the
   array corresponds to a brace-expanded pattern. Each item in the row
   corresponds to a single path-part. For example, the pattern
@@ -142,26 +152,20 @@ var mm = new Minimatch(pattern, options)
 
   If a portion of the pattern doesn't have any "magic" in it
   (that is, it's something like `"foo"` rather than `fo*o?`), then it
-  will be left as a string rather than converted to a regular
-  expression.
+  will be left as a string rather than converted to a `Matcher`.
+
+  A numeric range of 100 or more values, such as `{0..999}`, is
+  not expanded. It stays in one row, and the `Matcher` for its
+  portion tests for a number in the range.
 
-- `regexp` Created by the `makeRe` method. A single regular expression
-  expressing the entire pattern. This is useful in cases where you wish
-  to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
 - `negate` True if the pattern is negated.
 - `comment` True if the pattern is a comment.
 - `empty` True if the pattern is `""`.
 
 ### Methods
 
-- `makeRe()` Generate the `regexp` member if necessary, and return it.
-  Will return `false` if the pattern is invalid.
 - `match(fname)` Return true if the filename matches the pattern, or
   false otherwise.
-- `matchOne(fileArray, patternArray, partial)` Take a `/`-split
-  filename, and match it against a single row in the `regExpSet`. This
-  method is mainly for internal use, but is exposed so that it can be
-  used by a glob-walker that needs to avoid excessive filesystem calls.
 - `hasMagic()` Returns true if the parsed pattern contains any
   magic characters. Returns false if all comparator parts are
   string literals. If the `magicalBraces` option is set on the
@@ -185,16 +189,21 @@ All other methods are internal, and will be called as necessary.
 Main export. Tests a path against the pattern using the options.
 
 ```javascript
-var isJS = minimatch(file, '*.js', { matchBase: true })
+const isJS = minimatch(file, '*.js', { matchBase: true })
 ```
 
+It keeps at least the 256 `Minimatch` objects that it used most
+recently, so a pattern that it tests again with the same options
+is not compiled again. To test many paths against one pattern, a
+`Minimatch` object or `minimatch.filter()` is still a bit faster.
+
 ### minimatch.filter(pattern, options)
 
 Returns a function that tests its
 supplied argument, suitable for use with `Array.filter`. Example:
 
 ```javascript
-var javascripts = fileList.filter(
+const javascripts = fileList.filter(
   minimatch.filter('*.js', { matchBase: true }),
 )
 ```
@@ -208,6 +217,15 @@ If the `windowsPathsNoEscape` option is used, then characters are
 escaped by wrapping in `[]`, because a magic character wrapped in
 a character class can only be satisfied by that exact character.
 
+Braces (`{` and `}`) are only escaped if the `magicalBraces`
+option is set. Without it, a brace expansion in the input such as
+`{a,b}` is left as-is, and will be expanded when matching.
+
+A leading `!` or `#` is escaped, so that the result is never a
+negated pattern or a comment. In `windowsPathsNoEscape` mode, a
+leading `!` is written as `@(!)`, which only matches `!` (and
+matches nothing if `noext` is set).
+
 Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
 be escaped or unescaped.
 
@@ -234,21 +252,13 @@ files, in the style of fnmatch or glob. If nothing is matched, and
 options.nonull is set, then return a list containing the pattern itself.
 
 ```javascript
-var javascripts = minimatch.match(fileList, '*.js', { matchBase: true })
+const javascripts = minimatch.match(fileList, '*.js', { matchBase: true })
 ```
 
-### minimatch.makeRe(pattern, options)
-
-Make a regular expression object from the pattern.
-
 ## Options
 
 All options are `false` by default.
 
-### debug
-
-Dump a ton of stuff to stderr.
-
 ### nobrace
 
 Do not expand `{a,b}` and `{1..3}` brace sets.
@@ -271,11 +281,14 @@ Disable "extglob" style patterns like `+(a|b)`.
 
 ### nocase
 
-Perform a case-insensitive match.
+Perform a case-insensitive match. Case is folded one code point at
+a time, with Unicode simple case folding. See [Comparisons to other
+fnmatch/glob
+implementations](#comparisons-to-other-fnmatchglob-implementations).
 
 ### nocaseMagicOnly
 
-When used with `{nocase: true}`, create regular expressions that
+When used with `{nocase: true}`, create matchers that
 are case-insensitive, but leave string match portions untouched.
 Has no effect when used without `{nocase: true}`.
 
@@ -283,6 +296,28 @@ Useful when some other form of case-insensitive matching is used,
 or if the original string representation is useful in some other
 way.
 
+### normalize
+
+Normalize unicode in the pattern, and in each portion of the tested
+path, with this form: `'NFC'`, `'NFD'`, `'NFKC'`, or `'NFKD'`. `true`
+means `'NFC'`.
+
+A char such as `é` can be one code point, or `e` followed by a
+combining accent. Some file systems, such as on macOS, can give file
+names in the second form. Without this option, the two forms do not
+match.
+
+- The path is split on `/` before it is normalized. So with NFKC, a
+  full width `/` normalizes to `/`, but it does not split the path.
+  It is a char in its portion.
+- The syntax of the pattern is parsed before it is normalized. So
+  with NFKC, a full width `*` is a literal, which matches `*`, and
+  not a wildcard.
+- With `nocase`, the strings are normalized, and then case is folded.
+
+See [@isaacs/nonrecursive-glob-match](http://npm.im/@isaacs/nonrecursive-glob-match#unicode-normalization)
+for how classes and combining marks after wildcards are normalized.
+
 ### nonull
 
 When a match is not found by `minimatch.match`, return a list containing
@@ -354,7 +389,7 @@ For legacy reasons, this is also set if
 
 When a pattern starts with a UNC path or drive letter, and in
 `nocase:true` mode, do not convert the root portions of the
-pattern into a case-insensitive regular expression, and instead
+pattern into a case-insensitive matchers, and instead
 leave them as strings.
 
 This is the default when the platform is `win32` and
@@ -390,11 +425,15 @@ is equivalent in all cases).
   example, the pattern `./a/b/../*` is converted to `./a/*`, and
   so it will match the path string `./a/c`, but not the path
   string `./a/b/../c`. Dots and empty path portions in the
-  pattern are preserved.
+  pattern are preserved. On Windows, a `..` never removes the
+  drive letter or the UNC host and share at the start of a
+  pattern, the same as it never removes the `/` at the start of
+  a posix pattern. So `C:/a/../../x` is converted to `C:/../x`.
 - `2` (or higher) - Much more aggressive optimizations, suitable
   for use with file-walking cases:
   - Remove cases where a double-dot `..` follows a pattern
-    portion that is not `**`, `.`, or empty `''`. Remove empty
+    portion that is not `**`, `.`, or empty `''`, or a Windows
+    root as above. Remove empty
     and `.` portions of the pattern, where safe to do so (ie,
     anywhere other than the last position, the first position, or
     the second position in a pattern starting with `/`, as this
@@ -402,15 +441,17 @@ is equivalent in all cases).
   - Convert patterns containing `
/**/../

/` into the equivalent `

/{..,**}/

/`, where `

` is a a pattern portion other than `.`, `..`, `**`, or empty - `''`. - - Dedupe patterns where a `**` portion is present in one and - omitted in another, and it is not the final path portion, and - they are otherwise equivalent. So `{a/**/b,a/b}` becomes - `a/**/b`, because `**` matches against an empty path portion. - - Dedupe patterns where a `*` portion is present in one, and a - non-dot pattern other than `**`, `.`, `..`, or `''` is in the - same position in the other. So `a/{*,x}/b` becomes `a/*/b`, - because `*` can match against `x`. + `''`. If this would make more than `braceExpandMax` patterns, + or add more than 1,000,000 path portions in total, + construction throws a `RangeError`. + - Remove duplicate patterns. + - Remove a pattern when another pattern has `*` at one or more + positions, and the same portions at all other positions. The + portions that `*` replaces must be non-dot patterns other than + `**` or `''`. So `a/{*,x}/b` becomes `a/*/b`, because `*` can + match against `x`. This step is skipped when the number of + patterns times the number of different sets of `*` positions + is more than 100,000. While these optimizations improve the performance of file-walking use cases such as [glob](http://npm.im/glob) (ie, @@ -418,13 +459,6 @@ is equivalent in all cases). fail to match a literal string that would have been matched in optimization level 1 or 0. - Specifically, while the `Minimatch.match()` method will - optimize the file path string in the same ways, resulting in - the same matches, it will fail when tested with the regular - expression provided by `Minimatch.makeRe()`, unless the path - string is first processed with - `minimatch.levelTwoFileOptimize()` or similar. - ### platform When set to `win32`, this will trigger all windows-specific @@ -449,26 +483,6 @@ match the pattern provided. That is, this is an intentional false negative, deemed an acceptable break in correctness for security and performance. -### maxExtglobRecursion - -Max depth to traverse for nested extglobs like `*(a|b|c)` - -Default is 2, which is quite low, but any higher value swiftly -results in punishing performance impacts. Note that this is _not_ -relevant when the globstar types can be safely coalesced into a -single set. - -For example, `*(a|@(b|c)|d)` would be flattened into -`*(a|b|c|d)`. Thus, many common extglobs will retain good -performance and never hit this limit, even if they are -excessively deep and complicated. - -If the limit is hit, then the extglob characters are simply not -parsed, and the pattern effectively switches into `noextglob: -true` mode for the contents of that nested sub-pattern. This will -typically _not_ result in a match, but is considered a valid -trade-off for security and performance. - ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a @@ -497,8 +511,8 @@ If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than -`"*a?"`. This is akin to setting the `nullglob` option in bash, except -that it does not resolve escaped pattern characters. +`"*a?"`. This is like bash with the `nullglob` option off (the +default), except that bash also removes the escapes. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like @@ -506,20 +520,44 @@ other interpretation of the glob pattern. Thus, a pattern like **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. -Negated extglob patterns are handled as closely as possible to -Bash semantics, but there are some cases with negative extglobs -which are exceedingly difficult to express in a JavaScript -regular expression. In particular the negated pattern -`!(*|)*` will in bash match anything that does -not start with ``. However, -`!(*)*` _will_ match paths starting with -``, because the empty string can match against -the negated portion. In this library, `!(*|)*` -will _not_ match any pattern starting with ``, due to a -difference in precisely which patterns are considered "greedy" in -Regular Expressions vs bash path expansion. This may be fixable, -but not without incurring some complexity and performance costs, -and the trade-off seems to not be worth pursuing. +A numeric range of 100 or more values, such as `{0..999}` or +`{001..500}`, is the exception. It is not expanded, but it matches +the same strings as its expansion. A range is expanded as usual if +it has a step, such as `{0..999..2}`, if a `\` or `$` is before +it, if a `[` is before it in the same path portion, because it +might be inside a class, or if it is inside a `!(...)`, `*(...)` +or `+(...)` extglob, because those repeat or negate each value. + +Each portion of a pattern between `/` characters is matched with +[@isaacs/nonrecursive-glob-match](http://npm.im/@isaacs/nonrecursive-glob-match), +which uses Bash 5 as its reference, and does not use regular +expressions. So negated extglobs such as `!(*|)*` +match the same strings as in Bash. These are the known +differences: + +- If `dot` is not set, a portion that starts with `.` only matches + if a literal `.` in the pattern matches that first character. + Extglobs before that `.` can match the empty string, so the + pattern can still match. For example, with `nonegate`, + `!(.a|js)@(.*)` matches `.a`, `.a.js`, and `.js`, because + `!(.a|js)` matches the empty string. Bash does not match these + dotfiles. +- If an extglob such as `?(a` is not closed, Bash matches the + whole pattern as a literal string. In this library, only the + `?(` is literal, and the rest of the pattern is still matched + as a glob. So `a?(b*` matches `a?(bcc` here, but not in Bash. +- A pattern is split into portions on every `/`, including a `/` + inside an extglob. So `@(a|b/c)/*` becomes the portions + `@(a|b`, `c)`, and `*`, and its extglob is not closed. Bash + keeps the extglob whole, and drops each alternative with a `/` + in it, as no portion can contain a `/`. So in Bash, `@(a|b/c)/*` + is the same as `@(a)/*`. Leave out the alternatives with a `/` + to get the same result here. +- With `nocase`, case is folded one code point at a time with + Unicode simple case folding, the same as a JavaScript RegExp + with the `iu` flags. Bash uses the case functions of the C + library for the current locale, so its results can change with + the locale. Note that `fnmatch(3)` in libc is an extremely naive string comparison matcher, which does not do anything special for slashes. This library is diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.d.ts b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.d.ts deleted file mode 100644 index 74f2cf9322b97504fa4d6eb29dbe74222a4449ba..0000000000000000000000000000000000000000 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { MinimatchOptions, MMRegExp } from './index.js'; -export type ExtglobType = '!' | '?' | '+' | '*' | '@'; -export declare class AST { - #private; - type: ExtglobType | null; - id: number; - get depth(): number; - constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions); - get hasMagic(): boolean | undefined; - toString(): string; - push(...parts: (string | AST)[]): void; - toJSON(): unknown[]; - isStart(): boolean; - isEnd(): boolean; - copyIn(part: AST | string): void; - clone(parent: AST): AST; - static fromGlob(pattern: string, options?: MinimatchOptions): AST; - toMMPattern(): MMRegExp | string; - get options(): MinimatchOptions; - toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean]; -} -//# sourceMappingURL=ast.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.d.ts.map deleted file mode 100644 index 8965fd6a99ff91e22cd5de1f2c41563a673b8dc0..0000000000000000000000000000000000000000 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwC5D,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAgJrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;IAexB,EAAE,SAAO;IAET,IAAI,KAAK,IAAI,MAAM,CAElB;gBAgBC,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IAkDlB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAe/B,MAAM;IAkBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsQjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CA6OjE"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.js b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.js deleted file mode 100644 index 33df3769f3ca063f574b30d862942ba36b956a58..0000000000000000000000000000000000000000 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.js +++ /dev/null @@ -1,845 +0,0 @@ -"use strict"; -// parse a single path portion -var _a; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AST = void 0; -const brace_expressions_js_1 = require("./brace-expressions.js"); -const unescape_js_1 = require("./unescape.js"); -const types = new Set(['!', '?', '+', '*', '@']); -const isExtglobType = (c) => types.has(c); -const isExtglobAST = (c) => isExtglobType(c.type); -// Map of which extglob types can adopt the children of a nested extglob -// -// anything but ! can adopt a matching type: -// +(a|+(b|c)|d) => +(a|b|c|d) -// *(a|*(b|c)|d) => *(a|b|c|d) -// @(a|@(b|c)|d) => @(a|b|c|d) -// ?(a|?(b|c)|d) => ?(a|b|c|d) -// -// * can adopt anything, because 0 or repetition is allowed -// *(a|?(b|c)|d) => *(a|b|c|d) -// *(a|+(b|c)|d) => *(a|b|c|d) -// *(a|@(b|c)|d) => *(a|b|c|d) -// -// + can adopt @, because 1 or repetition is allowed -// +(a|@(b|c)|d) => +(a|b|c|d) -// -// + and @ CANNOT adopt *, because 0 would be allowed -// +(a|*(b|c)|d) => would match "", on *(b|c) -// @(a|*(b|c)|d) => would match "", on *(b|c) -// -// + and @ CANNOT adopt ?, because 0 would be allowed -// +(a|?(b|c)|d) => would match "", on ?(b|c) -// @(a|?(b|c)|d) => would match "", on ?(b|c) -// -// ? can adopt @, because 0 or 1 is allowed -// ?(a|@(b|c)|d) => ?(a|b|c|d) -// -// ? and @ CANNOT adopt * or +, because >1 would be allowed -// ?(a|*(b|c)|d) => would match bbb on *(b|c) -// @(a|*(b|c)|d) => would match bbb on *(b|c) -// ?(a|+(b|c)|d) => would match bbb on +(b|c) -// @(a|+(b|c)|d) => would match bbb on +(b|c) -// -// ! CANNOT adopt ! (nothing else can either) -// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c) -// -// ! can adopt @ -// !(a|@(b|c)|d) => !(a|b|c|d) -// -// ! CANNOT adopt * -// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed -// -// ! CANNOT adopt + -// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed -// -// ! CANNOT adopt ? -// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x" -const adoptionMap = new Map([ - ['!', ['@']], - ['?', ['?', '@']], - ['@', ['@']], - ['*', ['*', '+', '?', '@']], - ['+', ['+', '@']], -]); -// nested extglobs that can be adopted in, but with the addition of -// a blank '' element. -const adoptionWithSpaceMap = new Map([ - ['!', ['?']], - ['@', ['?']], - ['+', ['?', '*']], -]); -// union of the previous two maps -const adoptionAnyMap = new Map([ - ['!', ['?', '@']], - ['?', ['?', '@']], - ['@', ['?', '@']], - ['*', ['*', '+', '?', '@']], - ['+', ['+', '@', '?', '*']], -]); -// Extglobs that can take over their parent if they are the only child -// the key is parent, value maps child to resulting extglob parent type -// '@' is omitted because it's a special case. An `@` extglob with a single -// member can always be usurped by that subpattern. -const usurpMap = new Map([ - ['!', new Map([['!', '@']])], - [ - '?', - new Map([ - ['*', '*'], - ['+', '*'], - ]), - ], - [ - '@', - new Map([ - ['!', '!'], - ['?', '?'], - ['@', '@'], - ['*', '*'], - ['+', '+'], - ]), - ], - [ - '+', - new Map([ - ['?', '*'], - ['*', '*'], - ]), - ], -]); -// Patterns that get prepended to bind to the start of either the -// entire string, or just a single path portion, to prevent dots -// and/or traversal patterns, when needed. -// Exts don't need the ^ or / bit, because the root binds that already. -const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))'; -const startNoDot = '(?!\\.)'; -// characters that indicate a start of pattern needs the "no dots" bit, -// because a dot *might* be matched. ( is not in the list, because in -// the case of a child extglob, it will handle the prevention itself. -const addPatternStart = new Set(['[', '.']); -// cases where traversal is A-OK, no dot prevention needed -const justDots = new Set(['..', '.']); -const reSpecials = new Set('().*{}+?[]^$\\!'); -const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); -// any single thing other than / -const qmark = '[^/]'; -// * => any number of characters -const star = qmark + '*?'; -// use + when we need to ensure that *something* matches, because the * is -// the only thing in the path portion. -const starNoEmpty = qmark + '+?'; -// remove the \ chars that we added if we end up doing a nonmagic compare -// const deslash = (s: string) => s.replace(/\\(.)/g, '$1') -let ID = 0; -class AST { - type; - #root; - #hasMagic; - #uflag = false; - #parts = []; - #parent; - #parentIndex; - #negs; - #filledNegs = false; - #options; - #toString; - // set to true if it's an extglob with no children - // (which really means one child of '') - #emptyExt = false; - id = ++ID; - get depth() { - return (this.#parent?.depth ?? -1) + 1; - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return { - '@@type': 'AST', - id: this.id, - type: this.type, - root: this.#root.id, - parent: this.#parent?.id, - depth: this.depth, - partsLength: this.#parts.length, - parts: this.#parts, - }; - } - constructor(type, parent, options = {}) { - this.type = type; - // extglobs are inherently magical - if (type) - this.#hasMagic = true; - this.#parent = parent; - this.#root = this.#parent ? this.#parent.#root : this; - this.#options = this.#root === this ? options : this.#root.#options; - this.#negs = this.#root === this ? [] : this.#root.#negs; - if (type === '!' && !this.#root.#filledNegs) - this.#negs.push(this); - this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; - } - get hasMagic() { - /* c8 ignore start */ - if (this.#hasMagic !== undefined) - return this.#hasMagic; - /* c8 ignore stop */ - for (const p of this.#parts) { - if (typeof p === 'string') - continue; - if (p.type || p.hasMagic) - return (this.#hasMagic = true); - } - // note: will be undefined until we generate the regexp src and find out - return this.#hasMagic; - } - // reconstructs the pattern - toString() { - return (this.#toString !== undefined ? this.#toString - : !this.type ? - (this.#toString = this.#parts.map(p => String(p)).join('')) - : (this.#toString = - this.type + - '(' + - this.#parts.map(p => String(p)).join('|') + - ')')); - } - #fillNegs() { - /* c8 ignore start */ - if (this !== this.#root) - throw new Error('should only call on root'); - if (this.#filledNegs) - return this; - /* c8 ignore stop */ - // call toString() once to fill this out - this.toString(); - this.#filledNegs = true; - let n; - while ((n = this.#negs.pop())) { - if (n.type !== '!') - continue; - // walk up the tree, appending everthing that comes AFTER parentIndex - let p = n; - let pp = p.#parent; - while (pp) { - for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { - for (const part of n.#parts) { - /* c8 ignore start */ - if (typeof part === 'string') { - throw new Error('string part in extglob AST??'); - } - /* c8 ignore stop */ - part.copyIn(pp.#parts[i]); - } - } - p = pp; - pp = p.#parent; - } - } - return this; - } - push(...parts) { - for (const p of parts) { - if (p === '') - continue; - /* c8 ignore start */ - if (typeof p !== 'string' && - !(p instanceof _a && p.#parent === this)) { - throw new Error('invalid part: ' + p); - } - /* c8 ignore stop */ - this.#parts.push(p); - } - } - toJSON() { - const ret = this.type === null ? - this.#parts - .slice() - .map(p => (typeof p === 'string' ? p : p.toJSON())) - : [this.type, ...this.#parts.map(p => p.toJSON())]; - if (this.isStart() && !this.type) - ret.unshift([]); - if (this.isEnd() && - (this === this.#root || - (this.#root.#filledNegs && this.#parent?.type === '!'))) { - ret.push({}); - } - return ret; - } - isStart() { - if (this.#root === this) - return true; - // if (this.type) return !!this.#parent?.isStart() - if (!this.#parent?.isStart()) - return false; - if (this.#parentIndex === 0) - return true; - // if everything AHEAD of this is a negation, then it's still the "start" - const p = this.#parent; - for (let i = 0; i < this.#parentIndex; i++) { - const pp = p.#parts[i]; - if (!(pp instanceof _a && pp.type === '!')) { - return false; - } - } - return true; - } - isEnd() { - if (this.#root === this) - return true; - if (this.#parent?.type === '!') - return true; - if (!this.#parent?.isEnd()) - return false; - if (!this.type) - return this.#parent?.isEnd(); - // if not root, it'll always have a parent - /* c8 ignore start */ - const pl = this.#parent ? this.#parent.#parts.length : 0; - /* c8 ignore stop */ - return this.#parentIndex === pl - 1; - } - copyIn(part) { - if (typeof part === 'string') - this.push(part); - else - this.push(part.clone(this)); - } - clone(parent) { - const c = new _a(this.type, parent); - for (const p of this.#parts) { - c.copyIn(p); - } - return c; - } - static #parseAST(str, ast, pos, opt, extDepth) { - const maxDepth = opt.maxExtglobRecursion ?? 2; - let escaping = false; - let inBrace = false; - let braceStart = -1; - let braceNeg = false; - if (ast.type === null) { - // outside of a extglob, append until we find a start - let i = pos; - let acc = ''; - while (i < str.length) { - const c = str.charAt(i++); - // still accumulate escapes at this point, but we do ignore - // starts that are escaped - if (escaping || c === '\\') { - escaping = !escaping; - acc += c; - continue; - } - if (inBrace) { - if (i === braceStart + 1) { - if (c === '^' || c === '!') { - braceNeg = true; - } - } - else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { - inBrace = false; - } - acc += c; - continue; - } - else if (c === '[') { - inBrace = true; - braceStart = i; - braceNeg = false; - acc += c; - continue; - } - // we don't have to check for adoption here, because that's - // done at the other recursion point. - const doRecurse = !opt.noext && - isExtglobType(c) && - str.charAt(i) === '(' && - extDepth <= maxDepth; - if (doRecurse) { - ast.push(acc); - acc = ''; - const ext = new _a(c, ast); - i = _a.#parseAST(str, ext, i, opt, extDepth + 1); - ast.push(ext); - continue; - } - acc += c; - } - ast.push(acc); - return i; - } - // some kind of extglob, pos is at the ( - // find the next | or ) - let i = pos + 1; - let part = new _a(null, ast); - const parts = []; - let acc = ''; - while (i < str.length) { - const c = str.charAt(i++); - // still accumulate escapes at this point, but we do ignore - // starts that are escaped - if (escaping || c === '\\') { - escaping = !escaping; - acc += c; - continue; - } - if (inBrace) { - if (i === braceStart + 1) { - if (c === '^' || c === '!') { - braceNeg = true; - } - } - else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { - inBrace = false; - } - acc += c; - continue; - } - else if (c === '[') { - inBrace = true; - braceStart = i; - braceNeg = false; - acc += c; - continue; - } - const doRecurse = !opt.noext && - isExtglobType(c) && - str.charAt(i) === '(' && - /* c8 ignore start - the maxDepth is sufficient here */ - (extDepth <= maxDepth || (ast && ast.#canAdoptType(c))); - /* c8 ignore stop */ - if (doRecurse) { - const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1; - part.push(acc); - acc = ''; - const ext = new _a(c, part); - part.push(ext); - i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd); - continue; - } - if (c === '|') { - part.push(acc); - acc = ''; - parts.push(part); - part = new _a(null, ast); - continue; - } - if (c === ')') { - if (acc === '' && ast.#parts.length === 0) { - ast.#emptyExt = true; - } - part.push(acc); - acc = ''; - ast.push(...parts, part); - return i; - } - acc += c; - } - // unfinished extglob - // if we got here, it was a malformed extglob! not an extglob, but - // maybe something else in there. - ast.type = null; - ast.#hasMagic = undefined; - ast.#parts = [str.substring(pos - 1)]; - return i; - } - #canAdoptWithSpace(child) { - return this.#canAdopt(child, adoptionWithSpaceMap); - } - #canAdopt(child, map = adoptionMap) { - if (!child || - typeof child !== 'object' || - child.type !== null || - child.#parts.length !== 1 || - this.type === null) { - return false; - } - const gc = child.#parts[0]; - if (!gc || typeof gc !== 'object' || gc.type === null) { - return false; - } - return this.#canAdoptType(gc.type, map); - } - #canAdoptType(c, map = adoptionAnyMap) { - return !!map.get(this.type)?.includes(c); - } - #adoptWithSpace(child, index) { - const gc = child.#parts[0]; - const blank = new _a(null, gc, this.options); - blank.#parts.push(''); - gc.push(blank); - this.#adopt(child, index); - } - #adopt(child, index) { - const gc = child.#parts[0]; - this.#parts.splice(index, 1, ...gc.#parts); - for (const p of gc.#parts) { - if (typeof p === 'object') - p.#parent = this; - } - this.#toString = undefined; - } - #canUsurpType(c) { - const m = usurpMap.get(this.type); - return !!m?.has(c); - } - #canUsurp(child) { - if (!child || - typeof child !== 'object' || - child.type !== null || - child.#parts.length !== 1 || - this.type === null || - this.#parts.length !== 1) { - return false; - } - const gc = child.#parts[0]; - if (!gc || typeof gc !== 'object' || gc.type === null) { - return false; - } - return this.#canUsurpType(gc.type); - } - #usurp(child) { - const m = usurpMap.get(this.type); - const gc = child.#parts[0]; - const nt = m?.get(gc.type); - /* c8 ignore start - impossible */ - if (!nt) - return false; - /* c8 ignore stop */ - this.#parts = gc.#parts; - for (const p of this.#parts) { - if (typeof p === 'object') { - p.#parent = this; - } - } - this.type = nt; - this.#toString = undefined; - this.#emptyExt = false; - } - static fromGlob(pattern, options = {}) { - const ast = new _a(null, undefined, options); - _a.#parseAST(pattern, ast, 0, options, 0); - return ast; - } - // returns the regular expression if there's magic, or the unescaped - // string if not. - toMMPattern() { - // should only be called on root - /* c8 ignore start */ - if (this !== this.#root) - return this.#root.toMMPattern(); - /* c8 ignore stop */ - const glob = this.toString(); - const [re, body, hasMagic, uflag] = this.toRegExpSource(); - // if we're in nocase mode, and not nocaseMagicOnly, then we do - // still need a regular expression if we have to case-insensitively - // match capital/lowercase characters. - const anyMagic = hasMagic || - this.#hasMagic || - (this.#options.nocase && - !this.#options.nocaseMagicOnly && - glob.toUpperCase() !== glob.toLowerCase()); - if (!anyMagic) { - return body; - } - const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : ''); - return Object.assign(new RegExp(`^${re}$`, flags), { - _src: re, - _glob: glob, - }); - } - get options() { - return this.#options; - } - // returns the string match, the regexp source, whether there's magic - // in the regexp (so a regular expression is required) and whether or - // not the uflag is needed for the regular expression (for posix classes) - // TODO: instead of injecting the start/end at this point, just return - // the BODY of the regexp, along with the start/end portions suitable - // for binding the start/end in either a joined full-path makeRe context - // (where we bind to (^|/), or a standalone matchPart context (where - // we bind to ^, and not /). Otherwise slashes get duped! - // - // In part-matching mode, the start is: - // - if not isStart: nothing - // - if traversal possible, but not allowed: ^(?!\.\.?$) - // - if dots allowed or not possible: ^ - // - if dots possible and not allowed: ^(?!\.) - // end is: - // - if not isEnd(): nothing - // - else: $ - // - // In full-path matching mode, we put the slash at the START of the - // pattern, so start is: - // - if first pattern: same as part-matching mode - // - if not isStart(): nothing - // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) - // - if dots allowed or not possible: / - // - if dots possible and not allowed: /(?!\.) - // end is: - // - if last pattern, same as part-matching mode - // - else nothing - // - // Always put the (?:$|/) on negated tails, though, because that has to be - // there to bind the end of the negated pattern portion, and it's easier to - // just stick it in now rather than try to inject it later in the middle of - // the pattern. - // - // We can just always return the same end, and leave it up to the caller - // to know whether it's going to be used joined or in parts. - // And, if the start is adjusted slightly, can do the same there: - // - if not isStart: nothing - // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) - // - if dots allowed or not possible: (?:/|^) - // - if dots possible and not allowed: (?:/|^)(?!\.) - // - // But it's better to have a simpler binding without a conditional, for - // performance, so probably better to return both start options. - // - // Then the caller just ignores the end if it's not the first pattern, - // and the start always gets applied. - // - // But that's always going to be $ if it's the ending pattern, or nothing, - // so the caller can just attach $ at the end of the pattern when building. - // - // So the todo is: - // - better detect what kind of start is needed - // - return both flavors of starting pattern - // - attach $ at the end of the pattern when creating the actual RegExp - // - // Ah, but wait, no, that all only applies to the root when the first pattern - // is not an extglob. If the first pattern IS an extglob, then we need all - // that dot prevention biz to live in the extglob portions, because eg - // +(*|.x*) can match .xy but not .yx. - // - // So, return the two flavors if it's #root and the first child is not an - // AST, otherwise leave it to the child AST to handle it, and there, - // use the (?:^|/) style of start binding. - // - // Even simplified further: - // - Since the start for a join is eg /(?!\.) and the start for a part - // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root - // or start or whatever) and prepend ^ or / at the Regexp construction. - toRegExpSource(allowDot) { - const dot = allowDot ?? !!this.#options.dot; - if (this.#root === this) { - this.#flatten(); - this.#fillNegs(); - } - if (!isExtglobAST(this)) { - const noEmpty = this.isStart() && - this.isEnd() && - !this.#parts.some(s => typeof s !== 'string'); - const src = this.#parts - .map(p => { - const [re, _, hasMagic, uflag] = typeof p === 'string' ? - _a.#parseGlob(p, this.#hasMagic, noEmpty) - : p.toRegExpSource(allowDot); - this.#hasMagic = this.#hasMagic || hasMagic; - this.#uflag = this.#uflag || uflag; - return re; - }) - .join(''); - let start = ''; - if (this.isStart()) { - if (typeof this.#parts[0] === 'string') { - // this is the string that will match the start of the pattern, - // so we need to protect against dots and such. - // '.' and '..' cannot match unless the pattern is that exactly, - // even if it starts with . or dot:true is set. - const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); - if (!dotTravAllowed) { - const aps = addPatternStart; - // check if we have a possibility of matching . or .., - // and prevent that. - const needNoTrav = - // dots are allowed, and the pattern starts with [ or . - (dot && aps.has(src.charAt(0))) || - // the pattern starts with \., and then [ or . - (src.startsWith('\\.') && aps.has(src.charAt(2))) || - // the pattern starts with \.\., and then [ or . - (src.startsWith('\\.\\.') && aps.has(src.charAt(4))); - // no need to prevent dots if it can't match a dot, or if a - // sub-pattern will be preventing it anyway. - const needNoDot = !dot && !allowDot && aps.has(src.charAt(0)); - start = - needNoTrav ? startNoTraversal - : needNoDot ? startNoDot - : ''; - } - } - } - // append the "end of path portion" pattern to negation tails - let end = ''; - if (this.isEnd() && - this.#root.#filledNegs && - this.#parent?.type === '!') { - end = '(?:$|\\/)'; - } - const final = start + src + end; - return [ - final, - (0, unescape_js_1.unescape)(src), - (this.#hasMagic = !!this.#hasMagic), - this.#uflag, - ]; - } - // We need to calculate the body *twice* if it's a repeat pattern - // at the start, once in nodot mode, then again in dot mode, so a - // pattern like *(?) can match 'x.y' - const repeated = this.type === '*' || this.type === '+'; - // some kind of extglob - const start = this.type === '!' ? '(?:(?!(?:' : '(?:'; - let body = this.#partsToRegExp(dot); - if (this.isStart() && this.isEnd() && !body && this.type !== '!') { - // invalid extglob, has to at least be *something* present, if it's - // the entire path portion. - const s = this.toString(); - const me = this; - me.#parts = [s]; - me.type = null; - me.#hasMagic = undefined; - return [s, (0, unescape_js_1.unescape)(this.toString()), false, false]; - } - let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? - '' - : this.#partsToRegExp(true); - if (bodyDotAllowed === body) { - bodyDotAllowed = ''; - } - if (bodyDotAllowed) { - body = `(?:${body})(?:${bodyDotAllowed})*?`; - } - // an empty !() is exactly equivalent to a starNoEmpty - let final = ''; - if (this.type === '!' && this.#emptyExt) { - final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty; - } - else { - const close = this.type === '!' ? - // !() must match something,but !(x) can match '' - '))' + - (this.isStart() && !dot && !allowDot ? startNoDot : '') + - star + - ')' - : this.type === '@' ? ')' - : this.type === '?' ? ')?' - : this.type === '+' && bodyDotAllowed ? ')' - : this.type === '*' && bodyDotAllowed ? `)?` - : `)${this.type}`; - final = start + body + close; - } - return [ - final, - (0, unescape_js_1.unescape)(body), - (this.#hasMagic = !!this.#hasMagic), - this.#uflag, - ]; - } - #flatten() { - if (!isExtglobAST(this)) { - for (const p of this.#parts) { - if (typeof p === 'object') { - p.#flatten(); - } - } - } - else { - // do up to 10 passes to flatten as much as possible - let iterations = 0; - let done = false; - do { - done = true; - for (let i = 0; i < this.#parts.length; i++) { - const c = this.#parts[i]; - if (typeof c === 'object') { - c.#flatten(); - if (this.#canAdopt(c)) { - done = false; - this.#adopt(c, i); - } - else if (this.#canAdoptWithSpace(c)) { - done = false; - this.#adoptWithSpace(c, i); - } - else if (this.#canUsurp(c)) { - done = false; - this.#usurp(c); - } - } - } - } while (!done && ++iterations < 10); - } - this.#toString = undefined; - } - #partsToRegExp(dot) { - return this.#parts - .map(p => { - // extglob ASTs should only contain parent ASTs - /* c8 ignore start */ - if (typeof p === 'string') { - throw new Error('string type in extglob ast??'); - } - /* c8 ignore stop */ - // can ignore hasMagic, because extglobs are already always magic - const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot); - this.#uflag = this.#uflag || uflag; - return re; - }) - .filter(p => !(this.isStart() && this.isEnd()) || !!p) - .join('|'); - } - static #parseGlob(glob, hasMagic, noEmpty = false) { - let escaping = false; - let re = ''; - let uflag = false; - // multiple stars that aren't globstars coalesce into one * - let inStar = false; - for (let i = 0; i < glob.length; i++) { - const c = glob.charAt(i); - if (escaping) { - escaping = false; - re += (reSpecials.has(c) ? '\\' : '') + c; - continue; - } - if (c === '*') { - if (inStar) - continue; - inStar = true; - re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star; - hasMagic = true; - continue; - } - else { - inStar = false; - } - if (c === '\\') { - if (i === glob.length - 1) { - re += '\\\\'; - } - else { - escaping = true; - } - continue; - } - if (c === '[') { - const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i); - if (consumed) { - re += src; - uflag = uflag || needUflag; - i += consumed - 1; - hasMagic = hasMagic || magic; - continue; - } - } - if (c === '?') { - re += qmark; - hasMagic = true; - continue; - } - re += regExpEscape(c); - } - return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag]; - } -} -exports.AST = AST; -_a = AST; -//# sourceMappingURL=ast.js.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.js.map deleted file mode 100644 index 3498fb2631bc2968f6e8e7b04b5adbbe2f29e6ed..0000000000000000000000000000000000000000 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/ast.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ast.js","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":";AAAA,8BAA8B;;;;AAE9B,iEAAmD;AAEnD,+CAAwC;AAwCxC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAC7D,MAAM,aAAa,GAAG,CAAC,CAAgB,EAAoB,EAAE,CAC3D,KAAK,CAAC,GAAG,CAAC,CAAgB,CAAC,CAAA;AAC7B,MAAM,YAAY,GAAG,CAAC,CAAM,EAAoC,EAA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Class } from './brace-expressions.js'\nimport type { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n// 1 2 3 4 5 6 1 2 3 46 5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n// v----- .* because there's more following,\n// v v otherwise, .+ because it must be\n// v v *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n// copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string | null): c is ExtglobType =>\n types.has(c as ExtglobType)\nconst isExtglobAST = (c: AST): c is AST & { type: ExtglobType } =>\n isExtglobType(c.type)\n\n// Map of which extglob types can adopt the children of a nested extglob\n//\n// anything but ! can adopt a matching type:\n// +(a|+(b|c)|d) => +(a|b|c|d)\n// *(a|*(b|c)|d) => *(a|b|c|d)\n// @(a|@(b|c)|d) => @(a|b|c|d)\n// ?(a|?(b|c)|d) => ?(a|b|c|d)\n//\n// * can adopt anything, because 0 or repetition is allowed\n// *(a|?(b|c)|d) => *(a|b|c|d)\n// *(a|+(b|c)|d) => *(a|b|c|d)\n// *(a|@(b|c)|d) => *(a|b|c|d)\n//\n// + can adopt @, because 1 or repetition is allowed\n// +(a|@(b|c)|d) => +(a|b|c|d)\n//\n// + and @ CANNOT adopt *, because 0 would be allowed\n// +(a|*(b|c)|d) => would match \"\", on *(b|c)\n// @(a|*(b|c)|d) => would match \"\", on *(b|c)\n//\n// + and @ CANNOT adopt ?, because 0 would be allowed\n// +(a|?(b|c)|d) => would match \"\", on ?(b|c)\n// @(a|?(b|c)|d) => would match \"\", on ?(b|c)\n//\n// ? can adopt @, because 0 or 1 is allowed\n// ?(a|@(b|c)|d) => ?(a|b|c|d)\n//\n// ? and @ CANNOT adopt * or +, because >1 would be allowed\n// ?(a|*(b|c)|d) => would match bbb on *(b|c)\n// @(a|*(b|c)|d) => would match bbb on *(b|c)\n// ?(a|+(b|c)|d) => would match bbb on +(b|c)\n// @(a|+(b|c)|d) => would match bbb on +(b|c)\n//\n// ! CANNOT adopt ! (nothing else can either)\n// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)\n//\n// ! can adopt @\n// !(a|@(b|c)|d) => !(a|b|c|d)\n//\n// ! CANNOT adopt *\n// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed\n//\n// ! CANNOT adopt +\n// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed\n//\n// ! CANNOT adopt ?\n// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match \"x\"\nconst adoptionMap = new Map([\n ['!', ['@']],\n ['?', ['?', '@']],\n ['@', ['@']],\n ['*', ['*', '+', '?', '@']],\n ['+', ['+', '@']],\n])\n\n// nested extglobs that can be adopted in, but with the addition of\n// a blank '' element.\nconst adoptionWithSpaceMap = new Map([\n ['!', ['?']],\n ['@', ['?']],\n ['+', ['?', '*']],\n])\n\n// union of the previous two maps\nconst adoptionAnyMap = new Map([\n ['!', ['?', '@']],\n ['?', ['?', '@']],\n ['@', ['?', '@']],\n ['*', ['*', '+', '?', '@']],\n ['+', ['+', '@', '?', '*']],\n])\n\n// Extglobs that can take over their parent if they are the only child\n// the key is parent, value maps child to resulting extglob parent type\n// '@' is omitted because it's a special case. An `@` extglob with a single\n// member can always be usurped by that subpattern.\nconst usurpMap = new Map<\n ExtglobType,\n Map\n>([\n ['!', new Map([['!', '@']])],\n [\n '?',\n new Map([\n ['*', '*'],\n ['+', '*'],\n ]),\n ],\n [\n '@',\n new Map([\n ['!', '!'],\n ['?', '?'],\n ['@', '@'],\n ['*', '*'],\n ['+', '+'],\n ]),\n ],\n [\n '+',\n new Map([\n ['?', '*'],\n ['*', '*'],\n ]),\n ],\n])\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nlet ID = 0\nexport class AST {\n type: ExtglobType | null\n readonly #root: AST\n\n #hasMagic?: boolean\n #uflag: boolean = false\n #parts: (string | AST)[] = []\n #parent?: AST\n #parentIndex: number\n #negs: AST[]\n #filledNegs: boolean = false\n #options: MinimatchOptions\n #toString?: string\n // set to true if it's an extglob with no children\n // (which really means one child of '')\n #emptyExt: boolean = false\n id = ++ID\n\n get depth(): number {\n return (this.#parent?.depth ?? -1) + 1\n }\n\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return {\n '@@type': 'AST',\n id: this.id,\n type: this.type,\n root: this.#root.id,\n parent: this.#parent?.id,\n depth: this.depth,\n partsLength: this.#parts.length,\n parts: this.#parts,\n }\n }\n\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {},\n ) {\n this.type = type\n // extglobs are inherently magical\n if (type) this.#hasMagic = true\n this.#parent = parent\n this.#root = this.#parent ? this.#parent.#root : this\n this.#options = this.#root === this ? options : this.#root.#options\n this.#negs = this.#root === this ? [] : this.#root.#negs\n if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n }\n\n get hasMagic(): boolean | undefined {\n /* c8 ignore start */\n if (this.#hasMagic !== undefined) return this.#hasMagic\n /* c8 ignore stop */\n for (const p of this.#parts) {\n if (typeof p === 'string') continue\n if (p.type || p.hasMagic) return (this.#hasMagic = true)\n }\n // note: will be undefined until we generate the regexp src and find out\n return this.#hasMagic\n }\n\n // reconstructs the pattern\n toString(): string {\n return (\n this.#toString !== undefined ? this.#toString\n : !this.type ?\n (this.#toString = this.#parts.map(p => String(p)).join(''))\n : (this.#toString =\n this.type +\n '(' +\n this.#parts.map(p => String(p)).join('|') +\n ')')\n )\n }\n\n #fillNegs() {\n /* c8 ignore start */\n if (this !== this.#root) throw new Error('should only call on root')\n if (this.#filledNegs) return this\n /* c8 ignore stop */\n\n // call toString() once to fill this out\n this.toString()\n this.#filledNegs = true\n let n: AST | undefined\n while ((n = this.#negs.pop())) {\n if (n.type !== '!') continue\n // walk up the tree, appending everthing that comes AFTER parentIndex\n let p: AST | undefined = n\n let pp = p.#parent\n while (pp) {\n for (\n let i = p.#parentIndex + 1;\n !pp.type && i < pp.#parts.length;\n i++\n ) {\n for (const part of n.#parts) {\n /* c8 ignore start */\n if (typeof part === 'string') {\n throw new Error('string part in extglob AST??')\n }\n /* c8 ignore stop */\n part.copyIn(pp.#parts[i])\n }\n }\n p = pp\n pp = p.#parent\n }\n }\n return this\n }\n\n push(...parts: (string | AST)[]) {\n for (const p of parts) {\n if (p === '') continue\n /* c8 ignore start */\n if (\n typeof p !== 'string' &&\n !(p instanceof AST && p.#parent === this)\n ) {\n throw new Error('invalid part: ' + p)\n }\n /* c8 ignore stop */\n this.#parts.push(p)\n }\n }\n\n toJSON() {\n const ret: unknown[] =\n this.type === null ?\n this.#parts\n .slice()\n .map(p => (typeof p === 'string' ? p : p.toJSON()))\n : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n if (this.isStart() && !this.type) ret.unshift([])\n if (\n this.isEnd() &&\n (this === this.#root ||\n (this.#root.#filledNegs && this.#parent?.type === '!'))\n ) {\n ret.push({})\n }\n return ret\n }\n\n isStart(): boolean {\n if (this.#root === this) return true\n // if (this.type) return !!this.#parent?.isStart()\n if (!this.#parent?.isStart()) return false\n if (this.#parentIndex === 0) return true\n // if everything AHEAD of this is a negation, then it's still the \"start\"\n const p = this.#parent\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i]\n if (!(pp instanceof AST && pp.type === '!')) {\n return false\n }\n }\n return true\n }\n\n isEnd(): boolean {\n if (this.#root === this) return true\n if (this.#parent?.type === '!') return true\n if (!this.#parent?.isEnd()) return false\n if (!this.type) return this.#parent?.isEnd()\n // if not root, it'll always have a parent\n /* c8 ignore start */\n const pl = this.#parent ? this.#parent.#parts.length : 0\n /* c8 ignore stop */\n return this.#parentIndex === pl - 1\n }\n\n copyIn(part: AST | string) {\n if (typeof part === 'string') this.push(part)\n else this.push(part.clone(this))\n }\n\n clone(parent: AST) {\n const c = new AST(this.type, parent)\n for (const p of this.#parts) {\n c.copyIn(p)\n }\n return c\n }\n\n static #parseAST(\n str: string,\n ast: AST,\n pos: number,\n opt: MinimatchOptions,\n extDepth: number,\n ): number {\n const maxDepth = opt.maxExtglobRecursion ?? 2\n let escaping = false\n let inBrace = false\n let braceStart = -1\n let braceNeg = false\n if (ast.type === null) {\n // outside of a extglob, append until we find a start\n let i = pos\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n // we don't have to check for adoption here, because that's\n // done at the other recursion point.\n const doRecurse =\n !opt.noext &&\n isExtglobType(c) &&\n str.charAt(i) === '(' &&\n extDepth <= maxDepth\n if (doRecurse) {\n ast.push(acc)\n acc = ''\n const ext = new AST(c, ast)\n i = AST.#parseAST(str, ext, i, opt, extDepth + 1)\n ast.push(ext)\n continue\n }\n acc += c\n }\n ast.push(acc)\n return i\n }\n\n // some kind of extglob, pos is at the (\n // find the next | or )\n let i = pos + 1\n let part = new AST(null, ast)\n const parts: AST[] = []\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n const doRecurse =\n !opt.noext &&\n isExtglobType(c) &&\n str.charAt(i) === '(' &&\n /* c8 ignore start - the maxDepth is sufficient here */\n (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)))\n /* c8 ignore stop */\n if (doRecurse) {\n const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1\n part.push(acc)\n acc = ''\n const ext = new AST(c, part)\n part.push(ext)\n i = AST.#parseAST(str, ext, i, opt, extDepth + depthAdd)\n continue\n }\n if (c === '|') {\n part.push(acc)\n acc = ''\n parts.push(part)\n part = new AST(null, ast)\n continue\n }\n if (c === ')') {\n if (acc === '' && ast.#parts.length === 0) {\n ast.#emptyExt = true\n }\n part.push(acc)\n acc = ''\n ast.push(...parts, part)\n return i\n }\n acc += c\n }\n\n // unfinished extglob\n // if we got here, it was a malformed extglob! not an extglob, but\n // maybe something else in there.\n ast.type = null\n ast.#hasMagic = undefined\n ast.#parts = [str.substring(pos - 1)]\n return i\n }\n\n #canAdoptWithSpace(child?: AST | string): child is AST & {\n type: null\n parts: [AST & { type: ExtglobType }]\n } {\n return this.#canAdopt(child, adoptionWithSpaceMap)\n }\n\n #canAdopt(\n child?: AST | string,\n map: Map = adoptionMap,\n ): child is AST & {\n type: null\n parts: [AST & { type: ExtglobType }]\n } {\n if (\n !child ||\n typeof child !== 'object' ||\n child.type !== null ||\n child.#parts.length !== 1 ||\n this.type === null\n ) {\n return false\n }\n const gc = child.#parts[0]\n if (!gc || typeof gc !== 'object' || gc.type === null) {\n return false\n }\n return (this as AST & { type: ExtglobType }).#canAdoptType(\n gc.type,\n map,\n )\n }\n #canAdoptType(\n c: string,\n map: Map = adoptionAnyMap,\n ): c is ExtglobType {\n return !!map.get(this.type as ExtglobType)?.includes(c as ExtglobType)\n }\n\n #adoptWithSpace(\n this: AST & { type: ExtglobType },\n child: AST & {\n type: null\n },\n index: number,\n ) {\n const gc = child.#parts[0] as AST & { type: ExtglobType }\n const blank = new AST(null, gc, this.options)\n blank.#parts.push('')\n gc.push(blank)\n this.#adopt(child, index)\n }\n\n #adopt(\n child: AST & {\n type: null\n },\n index: number,\n ) {\n const gc = child.#parts[0] as AST & { type: ExtglobType }\n this.#parts.splice(index, 1, ...gc.#parts)\n for (const p of gc.#parts) {\n if (typeof p === 'object') p.#parent = this\n }\n this.#toString = undefined\n }\n\n #canUsurpType(c: string): boolean {\n const m = usurpMap.get(this.type as ExtglobType)\n return !!m?.has(c as ExtglobType)\n }\n\n #canUsurp(child?: AST | string): child is AST & {\n type: null\n parts: [AST & { type: ExtglobType }]\n } {\n if (\n !child ||\n typeof child !== 'object' ||\n child.type !== null ||\n child.#parts.length !== 1 ||\n this.type === null ||\n this.#parts.length !== 1\n ) {\n return false\n }\n const gc = child.#parts[0]\n if (!gc || typeof gc !== 'object' || gc.type === null) {\n return false\n }\n return (this as AST & { type: ExtglobType }).#canUsurpType(gc.type)\n }\n\n #usurp(this: AST & { type: ExtglobType }, child: AST & { type: null }) {\n const m = usurpMap.get(this.type as ExtglobType)\n const gc = child.#parts[0] as AST & { type: ExtglobType }\n const nt = m?.get(gc.type)\n /* c8 ignore start - impossible */\n if (!nt) return false\n /* c8 ignore stop */\n this.#parts = gc.#parts\n for (const p of this.#parts) {\n if (typeof p === 'object') {\n p.#parent = this\n }\n }\n this.type = nt\n this.#toString = undefined\n this.#emptyExt = false\n }\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n const ast = new AST(null, undefined, options)\n AST.#parseAST(pattern, ast, 0, options, 0)\n return ast\n }\n\n // returns the regular expression if there's magic, or the unescaped\n // string if not.\n toMMPattern(): MMRegExp | string {\n // should only be called on root\n /* c8 ignore start */\n if (this !== this.#root) return this.#root.toMMPattern()\n /* c8 ignore stop */\n const glob = this.toString()\n const [re, body, hasMagic, uflag] = this.toRegExpSource()\n // if we're in nocase mode, and not nocaseMagicOnly, then we do\n // still need a regular expression if we have to case-insensitively\n // match capital/lowercase characters.\n const anyMagic =\n hasMagic ||\n this.#hasMagic ||\n (this.#options.nocase &&\n !this.#options.nocaseMagicOnly &&\n glob.toUpperCase() !== glob.toLowerCase())\n if (!anyMagic) {\n return body\n }\n\n const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob,\n })\n }\n\n get options() {\n return this.#options\n }\n\n // returns the string match, the regexp source, whether there's magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it's easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it's going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it's better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it's not the first pattern,\n // and the start always gets applied.\n //\n // But that's always going to be $ if it's the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it's #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(\n allowDot?: boolean,\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n const dot = allowDot ?? !!this.#options.dot\n if (this.#root === this) {\n this.#flatten()\n this.#fillNegs()\n }\n if (!isExtglobAST(this)) {\n const noEmpty =\n this.isStart() &&\n this.isEnd() &&\n !this.#parts.some(s => typeof s !== 'string')\n const src = this.#parts\n .map(p => {\n const [re, _, hasMagic, uflag] =\n typeof p === 'string' ?\n AST.#parseGlob(p, this.#hasMagic, noEmpty)\n : p.toRegExpSource(allowDot)\n this.#hasMagic = this.#hasMagic || hasMagic\n this.#uflag = this.#uflag || uflag\n return re\n })\n .join('')\n\n let start = ''\n if (this.isStart()) {\n if (typeof this.#parts[0] === 'string') {\n // this is the string that will match the start of the pattern,\n // so we need to protect against dots and such.\n\n // '.' and '..' cannot match unless the pattern is that exactly,\n // even if it starts with . or dot:true is set.\n const dotTravAllowed =\n this.#parts.length === 1 && justDots.has(this.#parts[0])\n if (!dotTravAllowed) {\n const aps = addPatternStart\n // check if we have a possibility of matching . or ..,\n // and prevent that.\n const needNoTrav =\n // dots are allowed, and the pattern starts with [ or .\n (dot && aps.has(src.charAt(0))) ||\n // the pattern starts with \\., and then [ or .\n (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n // the pattern starts with \\.\\., and then [ or .\n (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n // no need to prevent dots if it can't match a dot, or if a\n // sub-pattern will be preventing it anyway.\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n start =\n needNoTrav ? startNoTraversal\n : needNoDot ? startNoDot\n : ''\n }\n }\n }\n\n // append the \"end of path portion\" pattern to negation tails\n let end = ''\n if (\n this.isEnd() &&\n this.#root.#filledNegs &&\n this.#parent?.type === '!'\n ) {\n end = '(?:$|\\\\/)'\n }\n const final = start + src + end\n return [\n final,\n unescape(src),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n // We need to calculate the body *twice* if it's a repeat pattern\n // at the start, once in nodot mode, then again in dot mode, so a\n // pattern like *(?) can match 'x.y'\n\n const repeated = this.type === '*' || this.type === '+'\n // some kind of extglob\n const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n let body = (this as AST & { type: ExtglobType }).#partsToRegExp(dot)\n\n if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n // invalid extglob, has to at least be *something* present, if it's\n // the entire path portion.\n const s = this.toString()\n const me = this as AST\n me.#parts = [s]\n me.type = null\n me.#hasMagic = undefined\n return [s, unescape(this.toString()), false, false]\n }\n\n let bodyDotAllowed =\n !repeated || allowDot || dot || !startNoDot ?\n ''\n : this.#partsToRegExp(true)\n if (bodyDotAllowed === body) {\n bodyDotAllowed = ''\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`\n }\n\n // an empty !() is exactly equivalent to a starNoEmpty\n let final = ''\n if (this.type === '!' && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n } else {\n const close =\n this.type === '!' ?\n // !() must match something,but !(x) can match ''\n '))' +\n (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n star +\n ')'\n : this.type === '@' ? ')'\n : this.type === '?' ? ')?'\n : this.type === '+' && bodyDotAllowed ? ')'\n : this.type === '*' && bodyDotAllowed ? `)?`\n : `)${this.type}`\n final = start + body + close\n }\n return [\n final,\n unescape(body),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n #flatten() {\n if (!isExtglobAST(this)) {\n for (const p of this.#parts) {\n if (typeof p === 'object') {\n p.#flatten()\n }\n }\n } else {\n // do up to 10 passes to flatten as much as possible\n let iterations = 0\n let done = false\n do {\n done = true\n for (let i = 0; i < this.#parts.length; i++) {\n const c = this.#parts[i]\n if (typeof c === 'object') {\n c.#flatten()\n if (this.#canAdopt(c)) {\n done = false\n this.#adopt(c, i)\n } else if (this.#canAdoptWithSpace(c)) {\n done = false\n ;(this as AST & { type: ExtglobType }).#adoptWithSpace(c, i)\n } else if (this.#canUsurp(c)) {\n done = false\n ;(this as AST & { type: ExtglobType }).#usurp(c)\n }\n }\n }\n } while (!done && ++iterations < 10)\n }\n this.#toString = undefined\n }\n\n #partsToRegExp(this: AST & { type: ExtglobType }, dot: boolean) {\n return this.#parts\n .map(p => {\n // extglob ASTs should only contain parent ASTs\n /* c8 ignore start */\n if (typeof p === 'string') {\n throw new Error('string type in extglob ast??')\n }\n /* c8 ignore stop */\n // can ignore hasMagic, because extglobs are already always magic\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n this.#uflag = this.#uflag || uflag\n return re\n })\n .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n .join('|')\n }\n\n static #parseGlob(\n glob: string,\n hasMagic: boolean | undefined,\n noEmpty: boolean = false,\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n let escaping = false\n let re = ''\n let uflag = false\n // multiple stars that aren't globstars coalesce into one *\n let inStar = false\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i)\n if (escaping) {\n escaping = false\n re += (reSpecials.has(c) ? '\\\\' : '') + c\n continue\n }\n if (c === '*') {\n if (inStar) continue\n inStar = true\n re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star\n hasMagic = true\n continue\n } else {\n inStar = false\n }\n if (c === '\\\\') {\n if (i === glob.length - 1) {\n re += '\\\\\\\\'\n } else {\n escaping = true\n }\n continue\n }\n if (c === '[') {\n const [src, needUflag, consumed, magic] = parseClass(glob, i)\n if (consumed) {\n re += src\n uflag = uflag || needUflag\n i += consumed - 1\n hasMagic = hasMagic || magic\n continue\n }\n }\n if (c === '?') {\n re += qmark\n hasMagic = true\n continue\n }\n re += regExpEscape(c)\n }\n return [re, unescape(glob), !!hasMagic, uflag]\n }\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts deleted file mode 100644 index b1572deb95e2e376474f9fc1e56e4c38a055fbd1..0000000000000000000000000000000000000000 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export type ParseClassResult = [ - src: string, - uFlag: boolean, - consumed: number, - hasMagic: boolean -]; -export declare const parseClass: (glob: string, position: number) => ParseClassResult; -//# sourceMappingURL=brace-expressions.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map deleted file mode 100644 index 09b4c11060de7850a23ad17948c7d5d674850576..0000000000000000000000000000000000000000 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AAgCA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,KACf,gBA2HF,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.js.map deleted file mode 100644 index 3cc3b343b530fda9adc37982e4d80d6ac654d673..0000000000000000000000000000000000000000 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/brace-expressions.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"brace-expressions.js","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,wCAAwC;;;AAExC,8DAA8D;AAC9D,MAAM,YAAY,GAChB;IACE,WAAW,EAAE,CAAC,sBAAsB,EAAE,IAAI,CAAC;IAC3C,WAAW,EAAE,CAAC,eAAe,EAAE,IAAI,CAAC;IACpC,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC;IAC7C,WAAW,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC;IACjC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,EAAE,IAAI,CAAC;IACzC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,uBAAuB,EAAE,IAAI,CAAC;IAC5C,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,UAAU,EAAE,CAAC,6BAA6B,EAAE,IAAI,CAAC;IACjD,YAAY,EAAE,CAAC,WAAW,EAAE,KAAK,CAAC;CACnC,CAAA;AAEH,+DAA+D;AAC/D,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,CAAC,CAAA;AAC1C,CAAC,CAAA;AA9HY,QAAA,UAAU,cA8HtB","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } =\n {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n '[:cntrl:]': ['\\\\p{Cc}', true],\n '[:digit:]': ['\\\\p{Nd}', true],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n '[:lower:]': ['\\\\p{Ll}', true],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}', true],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n '[:upper:]': ['\\\\p{Lu}', true],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n '[:xdigit:]': ['A-Fa-f0-9', false],\n }\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n src: string,\n uFlag: boolean,\n consumed: number,\n hasMagic: boolean,\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n glob: string,\n position: number,\n): ParseClassResult => {\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let uflag = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return ['$.', false, glob.length - pos, true]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n uflag = uflag || u\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c))\n }\n rangeStart = ''\n i++\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + 1)) {\n ranges.push(braceEscape(c + '-'))\n i += 2\n continue\n }\n if (glob.startsWith('-', i + 1)) {\n rangeStart = c\n i += 2\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(c))\n i++\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return ['', false, 0, false]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return ['$.', false, glob.length - pos, true]\n }\n\n // if we got one positive range, and it's a single character, then that's\n // not actually a magic pattern, it's just that one literal character.\n // we should not treat that as \"magic\", we should just return the literal\n // character. [_] is a perfectly valid way to escape glob magic chars.\n if (\n negs.length === 0 &&\n ranges.length === 1 &&\n /^\\\\?.$/.test(ranges[0]) &&\n !negate\n ) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n return [regexpEscape(r), false, endPos - pos, false]\n }\n\n const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n const comb =\n ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs\n\n return [comb, uflag, endPos - pos, true]\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.d.ts b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.d.ts index 141024a06bdf747fe6d6ecc48a80675dff795800..202b981612906fd1b56445fb2fcb2aae54fd9103 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.d.ts +++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.d.ts @@ -10,6 +10,10 @@ import type { MinimatchOptions } from './index.js'; * * If the {@link MinimatchOptions.magicalBraces} option is used, * then braces (`{` and `}`) will be escaped. + * + * A leading `#` or `!` is escaped as well, so that the result is never a + * comment or a negated pattern. In `windowsPathsNoEscape` mode, a leading + * `!` is written as `@(!)`, because `[!` starts a negated class. */ export declare const escape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick) => string; //# sourceMappingURL=escape.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.d.ts.map index e167e30065a04e54a37b3f6e6b44275c42c3c602..ad38ae9f582b9c6a20d9e02df2b4dfec0b729429 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.d.ts.map +++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,MAAM,GACjB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAazE,CAAA"} \ No newline at end of file +{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,MAAM,GACjB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAyBzE,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.js b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.js index 83a713a25507707b9071cc1a93be5a8fc20affd9..97b38008013cf9e71430473d2531cab14223ca21 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.js +++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.js @@ -12,19 +12,34 @@ exports.escape = void 0; * * If the {@link MinimatchOptions.magicalBraces} option is used, * then braces (`{` and `}`) will be escaped. + * + * A leading `#` or `!` is escaped as well, so that the result is never a + * comment or a negated pattern. In `windowsPathsNoEscape` mode, a leading + * `!` is written as `@(!)`, because `[!` starts a negated class. */ const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => { // don't need to escape +@! because we escape the parens // that make those magic, and escaping ! as [!] isn't valid, // because [!]] is a valid glob class meaning not ']'. - if (magicalBraces) { - return windowsPathsNoEscape ? - s.replace(/[?*()[\]{}]/g, '[$&]') - : s.replace(/[?*()[\]\\{}]/g, '\\$&'); + // However, at the start of the pattern, '!' negates the pattern and + // '#' makes it a comment, so the first character is handled below. + const e = magicalBraces ? + windowsPathsNoEscape ? s.replace(/[?*()[\]{}]/g, '[$&]') + : s.replace(/[?*()[\]\\{}]/g, '\\$&') + : windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, '[$&]') + : s.replace(/[?*()[\]\\]/g, '\\$&'); + const c = e.charAt(0); + if (c === '#') { + return (windowsPathsNoEscape ? '[#]' : '\\#') + e.slice(1); + } + if (c === '!') { + // '[!]' can not be used, because '[!' starts a negated class, and + // '\' is a path separator in windowsPathsNoEscape mode. '@(!)' + // matches only '!'. If extglobs are disabled with `noext`, it + // matches nothing, rather than everything. + return (windowsPathsNoEscape ? '@(!)' : '\\!') + e.slice(1); } - return windowsPathsNoEscape ? - s.replace(/[?*()[\]]/g, '[$&]') - : s.replace(/[?*()[\]\\]/g, '\\$&'); + return e; }; exports.escape = escape; //# sourceMappingURL=escape.js.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.js.map index f963f0a14ae877630cc9542b82ee1b5365621c33..11fb1d5dff44cec46a8fbc6749ab03eda408e00a 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.js.map +++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/escape.js.map @@ -1 +1 @@ -{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;GAWG;AACI,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,KAAK,MAC+C,EAAE,EACxE,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC;YACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAA;IACzC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA;AAlBY,QAAA,MAAM,UAkBlB","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = false,\n }: Pick = {},\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n if (magicalBraces) {\n return windowsPathsNoEscape ?\n s.replace(/[?*()[\\]{}]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n }\n return windowsPathsNoEscape ?\n s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n"]} \ No newline at end of file +{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;GAeG;AACI,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,KAAK,MAC+C,EAAE,EACxE,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,oEAAoE;IACpE,mEAAmE;IACnE,MAAM,CAAC,GACL,aAAa,CAAC,CAAC;QACb,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC;YACxD,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC;QACvC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;YACxD,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;IACrC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;IACrB,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;QACd,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC5D,CAAC;IACD,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;QACd,kEAAkE;QAClE,+DAA+D;QAC/D,8DAA8D;QAC9D,2CAA2C;QAC3C,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC7D,CAAC;IACD,OAAO,CAAC,CAAA;AACV,CAAC,CAAA;AA9BY,QAAA,MAAM,UA8BlB","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n *\n * A leading `#` or `!` is escaped as well, so that the result is never a\n * comment or a negated pattern. In `windowsPathsNoEscape` mode, a leading\n * `!` is written as `@(!)`, because `[!` starts a negated class.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n magicalBraces = false,\n }: Pick = {},\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n // However, at the start of the pattern, '!' negates the pattern and\n // '#' makes it a comment, so the first character is handled below.\n const e =\n magicalBraces ?\n windowsPathsNoEscape ? s.replace(/[?*()[\\]{}]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n : windowsPathsNoEscape ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n const c = e.charAt(0)\n if (c === '#') {\n return (windowsPathsNoEscape ? '[#]' : '\\\\#') + e.slice(1)\n }\n if (c === '!') {\n // '[!]' can not be used, because '[!' starts a negated class, and\n // '\\' is a path separator in windowsPathsNoEscape mode. '@(!)'\n // matches only '!'. If extglobs are disabled with `noext`, it\n // matches nothing, rather than everything.\n return (windowsPathsNoEscape ? '@(!)' : '\\\\!') + e.slice(1)\n }\n return e\n}\n"]} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.d.ts b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.d.ts index 7e1fc2edaadbe09033faefbd7363f0cba109bafc..4a485677d293d846ea4f5dade134d166da200f16 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.d.ts +++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.d.ts @@ -1,4 +1,4 @@ -import { AST } from './ast.js'; +import { Matcher, type Form } from '@isaacs/nonrecursive-glob-match'; export type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; export interface MinimatchOptions { /** do not expand `{x,y}` style braces */ @@ -7,8 +7,6 @@ export interface MinimatchOptions { nocomment?: boolean; /** do not treat patterns starting with `!` as a negation */ nonegate?: boolean; - /** print LOTS of debugging output */ - debug?: boolean; /** treat `**` the same as `*` */ noglobstar?: boolean; /** do not expand extglobs like `+(a|b)` */ @@ -37,6 +35,11 @@ export interface MinimatchOptions { nocase?: boolean; /** ignore case only in wildcard patterns */ nocaseMagicOnly?: boolean; + /** + * Normalize unicode in the pattern and in each portion of the + * tested paths, with this form. `true` means `'NFC'`. + */ + normalize?: boolean | Form; /** consider braces to be "magic" for the purpose of `hasMagic` */ magicalBraces?: boolean; /** @@ -53,6 +56,9 @@ export interface MinimatchOptions { /** * A number indicating the level of optimization that should be done * to the pattern prior to parsing and using it for matches. + * At level 2 or higher, throws RangeError if splitting `**` and `..` + * would make more than `braceExpandMax` patterns, or add more than + * 1,000,000 path portions. */ optimizationLevel?: number; /** operating system platform */ @@ -69,6 +75,10 @@ export interface MinimatchOptions { windowsNoMagicRoot?: boolean; /** * max number of `{...}` patterns to expand. Default 100_000. + * + * At `optimizationLevel` 2 or higher, this also limits the + * patterns made when `**` is followed by `..`. Over this limit, + * construction throws a RangeError. */ braceExpandMax?: number; /** @@ -78,27 +88,6 @@ export interface MinimatchOptions { * and can handle absurdly excessive patterns. */ maxGlobstarRecursion?: number; - /** - * Max depth to traverse for nested extglobs like `*(a|b|c)` - * - * Default is 2, which is quite low, but any higher value - * swiftly results in punishing performance impacts. Note - * that this is *not* relevant when the globstar types can - * be safely coalesced into a single set. - * - * For example, `*(a|@(b|c)|d)` would be flattened into - * `*(a|b|c|d)`. Thus, many common extglobs will retain good - * performance and never hit this limit, even if they are - * excessively deep and complicated. - * - * If the limit is hit, then the extglob characters are simply - * not parsed, and the pattern effectively switches into - * `noextglob: true` mode for the contents of that nested - * sub-pattern. This will typically _not_ result in a match, - * but is considered a valid trade-off for security and - * performance. - */ - maxExtglobRecursion?: number; } export declare const minimatch: { (p: string, pattern: string, options?: MinimatchOptions): boolean; @@ -107,9 +96,7 @@ export declare const minimatch: { filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; defaults: (def: MinimatchOptions) => typeof minimatch; braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; - makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; - AST: typeof AST; Minimatch: typeof Minimatch; escape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick) => string; unescape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick) => string; @@ -120,13 +107,46 @@ export declare const GLOBSTAR: unique symbol; export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; export declare const defaults: (def: MinimatchOptions) => typeof minimatch; export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; -export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; -export type MMRegExp = RegExp & { - _src?: string; - _glob?: string; +/** + * A path that Minimatch#match split, with the settings that the split + * depends on. `resolved` is the parts after optimizationLevel 2 has + * resolved `.` and `..` in them, which only depends on the same + * settings, once a level 2 Minimatch has needed them. + */ +export type SplitPath = { + f: string; + isWindows: boolean; + preserveMultipleSlashes: boolean; + normalize: Form | undefined; + parts: string[]; + resolved?: string[]; +}; +export type ParseReturnFiltered = string | Matcher | typeof GLOBSTAR; +/** + * The rows that Minimatch#match can match without splitting the path: + * `**` and one more portion (`tail`), a portion with `**` on each side + * of it (`mid`), a portion and then `**` (`head`), or one portion that + * matches the basename of the path, with matchBase (`base`). + */ +export type RowShape = 'tail' | 'mid' | 'head' | 'base'; +/** + * The separators that a path has: only `/`, only `\` (a Windows path + * with no `/`), or both. Scanning for the ones it has is faster. + */ +export type PathSeps = '/' | '\\' | 'both'; +/** + * A pattern row split on its first and last `**`, from a start + * index. Each body segment has the number of path portions that it + * and the ones after it need, to find the last index where it can + * start in a path. + */ +export type GlobstarParts = { + head: ParseReturn[]; + body: ParseReturn[]; + tail: ParseReturn[]; + segments: [segment: ParseReturn[], need: number][]; }; -export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR; export type ParseReturn = ParseReturnFiltered | false; export declare class Minimatch { #private; @@ -147,28 +167,22 @@ export declare class Minimatch { platform: Platform; windowsNoMagicRoot: boolean; maxGlobstarRecursion: number; - regexp: false | null | MMRegExp; constructor(pattern: string, options?: MinimatchOptions); hasMagic(): boolean; - debug(..._: unknown[]): void; make(): void; + mergeRows(): void; preprocess(globParts: string[][]): string[][]; adjascentGlobstarOptimize(globParts: string[][]): string[][]; levelOneOptimize(globParts: string[][]): string[][]; - levelTwoFileOptimize(parts: string | string[]): string[]; firstPhasePreProcess(globParts: string[][]): string[][]; secondPhasePreProcess(globParts: string[][]): string[][]; - partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[]; parseNegate(): void; - matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean; braceExpand(): string[]; parse(pattern: string): ParseReturn; - makeRe(): false | MMRegExp; - slashSplit(p: string): string[]; match(f: string, partial?: boolean): boolean; static defaults(def: MinimatchOptions): typeof Minimatch; } -export { AST } from './ast.js'; export { escape } from './escape.js'; export { unescape } from './unescape.js'; +export type { Form }; //# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.d.ts.map index 7620db91cc81855821dded14c51fdfe9b0cd1d6a..0c296235759caedacd9eed307fab13dcb99b656f 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.d.ts.map +++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"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,CAAA"} \ No newline at end of file diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.js b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.js index 5a6983481b78583d75c89a17c5a8371b059171ff..2d2a2f8107271873ba516f5be64c7eb30002feeb 100644 --- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.js +++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.js @@ -1,77 +1,188 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; +exports.unescape = exports.escape = exports.Minimatch = exports.match = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; const brace_expansion_1 = require("brace-expansion"); +const nonrecursive_glob_match_1 = require("@isaacs/nonrecursive-glob-match"); const assert_valid_pattern_js_1 = require("./assert-valid-pattern.js"); -const ast_js_1 = require("./ast.js"); const escape_js_1 = require("./escape.js"); const unescape_js_1 = require("./unescape.js"); -const minimatch = (p, pattern, options = {}) => { +const DEFAULT_BRACE_EXPAND_MAX = 100_000; +const DEFAULT_GLOB_STAR_RECURSION_MAX = 200; +// avoid the annoying deprecation flag lol +const AWE_KEY = ('allowWindow' + 'sEscape'); +const minimatch = (p, pattern, options) => { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { + if (!options?.nocomment && pattern.charAt(0) === '#') { return false; } - return new Minimatch(pattern, options).match(p); + return cachedMinimatch(pattern, options).match(p); }; exports.minimatch = minimatch; -// Optimized checking for the most common glob patterns. -const starDotExtRE = /^\*+([^+@!?*[(]*)$/; -const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); -const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); -const starDotExtTestNocase = (ext) => { - ext = ext.toLowerCase(); - return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); -}; -const starDotExtTestNocaseDot = (ext) => { - ext = ext.toLowerCase(); - return (f) => f.toLowerCase().endsWith(ext); -}; -const starDotStarRE = /^\*+\.\*+$/; -const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); -const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); -const dotStarRE = /^\.\*+$/; -const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); -const starRE = /^\*+$/; -const starTest = (f) => f.length !== 0 && !f.startsWith('.'); -const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; -const qmarksRE = /^\?+([^+@!?*[(]*)?$/; -const qmarksTestNocase = ([$0, ext = '']) => { - const noext = qmarksTestNoExt([$0]); - if (!ext) - return noext; - ext = ext.toLowerCase(); - return (f) => noext(f) && f.toLowerCase().endsWith(ext); -}; -const qmarksTestNocaseDot = ([$0, ext = '']) => { - const noext = qmarksTestNoExtDot([$0]); - if (!ext) - return noext; - ext = ext.toLowerCase(); - return (f) => noext(f) && f.toLowerCase().endsWith(ext); -}; -const qmarksTestDot = ([$0, ext = '']) => { - const noext = qmarksTestNoExtDot([$0]); - return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +// The Minimatch objects that minimatch() used most recently, by options +// and then by pattern. When the cache is full, it becomes the old one, +// and the objects used from the old one are moved back to a new one. +// So it keeps 256 to 512 objects. +// The patterns can come from users, so the cache is also bounded by +// the total weight of the objects (see cacheWeight()), and an object +// that is too heavy is never kept. Otherwise a few unique patterns +// with large brace expansions would fill the heap. +let cache = new Map(); +let oldCache = new Map(); +let cacheSize = 0; +let cacheTotalWeight = 0; +const cacheMax = 256; +const cacheMaxWeight = 1 << 15; +const cacheMaxEntryWeight = 1 << 12; +// About the memory that a compiled object keeps: the pattern and the +// expanded patterns, of which each row in set is made. +const cacheWeight = (mm) => { + let w = mm.pattern.length; + for (const s of mm.globSet) { + w += s.length + 1; + if (w > cacheMaxEntryWeight) + break; + } + return w; }; -const qmarksTest = ([$0, ext = '']) => { - const noext = qmarksTestNoExt([$0]); - return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +// tsc fails here if a new option is in neither type. Add it to +// optionsKey() too. +const allOptionsKeyed = true; +void allOptionsKeyed; +// 0, 1 or 2 for undefined, falsy or truthy. +const tri = (v) => v === undefined ? 0 + : v ? 2 + : 1; +// The weight of each boolean option's base-3 digit in the key. The +// weights below 24 are for optimizationLevel (1), platform (3) and +// windowsPathsNoEscape (12). tsc fails here if a boolean option is +// not in the list. +const booleanWeights = new Map(Object.keys({ + nobrace: 0, + nocomment: 0, + nonegate: 0, + noglobstar: 0, + noext: 0, + nonull: 0, + partial: 0, + dot: 0, + nocase: 0, + nocaseMagicOnly: 0, + magicalBraces: 0, + matchBase: 0, + flipNegate: 0, + preserveMultipleSlashes: 0, + windowsNoMagicRoot: 0, +}).map((k, i) => [k, 24 * 3 ** i])); +// The cache key for a set of options. It is a number, unless an +// option is set to a value that the number can not show, such as +// normalize or an uncommon platform. Then it is a JSON string. +// The defaults give 0, the same key as no options. +// It only reads the keys that are set, so that the speed does not +// depend on the shape of the options object. +const optionsKey = (o) => { + let n = 0; + let wpe = false; + // inherited keys too, because Minimatch reads them + // oxlint-disable-next-line guard-for-in + for (const k in o) { + const v = o[k]; + switch (k) { + // the same test as the Minimatch constructor + case 'windowsPathsNoEscape': + if (v) + wpe = true; + break; + case AWE_KEY: + if (v === false) + wpe = true; + break; + case 'platform': { + // the same test as the Minimatch constructor + const p = v || defaultPlatform; + if (p === defaultPlatform) + break; + if (p === 'darwin') + n += 3; + else if (p === 'win32') + n += 6; + else if (p === 'linux') + n += 9; + else + return JSON.stringify(o); + break; + } + case 'optimizationLevel': + // The same tests as Minimatch: 1 when undefined, then >= 2, + // >= 1, or else 0. The default level 1 adds 0. + if (v === undefined) + break; + n += + v >= 2 ? 1 + : v >= 1 ? 0 + : 2; + break; + case 'braceExpandMax': + if (v !== undefined && v !== DEFAULT_BRACE_EXPAND_MAX) { + return JSON.stringify(o); + } + break; + case 'maxGlobstarRecursion': + if (v !== undefined && v !== DEFAULT_GLOB_STAR_RECURSION_MAX) { + return JSON.stringify(o); + } + break; + case 'normalize': + if (v !== undefined) + return JSON.stringify(o); + break; + default: + // unknown keys have no weight + n += (booleanWeights.get(k) ?? 0) * tri(v); + } + } + return wpe ? n + 12 : n; }; -const qmarksTestNoExt = ([$0]) => { - const len = $0.length; - return (f) => f.length === len && !f.startsWith('.'); +// A copy, so a later change to the options can not change it. Unlike +// a spread, it keeps the inherited keys, which optionsKey() and the +// Minimatch constructor also read. +const copyOptions = (o) => { + const copy = {}; + // oxlint-disable-next-line guard-for-in + for (const k in o) + copy[k] = o[k]; + return copy; }; -const qmarksTestNoExtDot = ([$0]) => { - const len = $0.length; - return (f) => f.length === len && f !== '.' && f !== '..'; +const cachedMinimatch = (pattern, options) => { + const key = options ? optionsKey(options) : 0; + let mm = cache.get(key)?.get(pattern); + if (mm) + return mm; + mm = + oldCache.get(key)?.get(pattern) ?? + new Minimatch(pattern, copyOptions(options)); + const weight = cacheWeight(mm); + // too big to keep, so it is compiled again each time + if (weight > cacheMaxEntryWeight) + return mm; + if (cacheSize >= cacheMax || + cacheTotalWeight + weight > cacheMaxWeight) { + oldCache = cache; + cache = new Map(); + cacheSize = 0; + cacheTotalWeight = 0; + } + let byPattern = cache.get(key); + if (!byPattern) + cache.set(key, (byPattern = new Map())); + byPattern.set(pattern, mm); + cacheSize++; + cacheTotalWeight += weight; + return mm; }; /* c8 ignore start */ const defaultPlatform = (typeof process === 'object' && process ? - (typeof process.env === 'object' && - process.env && - process.env.__MINIMATCH_TESTING_PLATFORM__) || - process.platform + process.env?.__MINIMATCH_TESTING_PLATFORM__ || process.platform : 'posix'); const path = { win32: { sep: '\\' }, @@ -82,19 +193,10 @@ exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep; exports.minimatch.sep = exports.sep; exports.GLOBSTAR = Symbol('globstar **'); exports.minimatch.GLOBSTAR = exports.GLOBSTAR; -// any single thing other than / -// don't need to escape / when using new RegExp() -const qmark = '[^/]'; -// * => any number of characters -const star = qmark + '*?'; -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; -const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); +const filter = (pattern, options) => { + let mm; + return (p) => (mm ??= cachedMinimatch(pattern, options)).match(p); +}; exports.filter = filter; exports.minimatch.filter = exports.filter; const ext = (a, b = {}) => Object.assign({}, a, b); @@ -113,21 +215,10 @@ const defaults = (def) => { return orig.defaults(ext(def, options)).Minimatch; } }, - AST: class AST extends orig.AST { - /* c8 ignore start */ - constructor(type, parent, options = {}) { - super(type, parent, ext(def, options)); - } - /* c8 ignore stop */ - static fromGlob(pattern, options = {}) { - return orig.AST.fromGlob(pattern, ext(def, options)); - } - }, unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), escape: (s, options = {}) => orig.escape(s, ext(def, options)), filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), defaults: (options) => orig.defaults(ext(def, options)), - makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), sep: orig.sep, @@ -154,24 +245,57 @@ const braceExpand = (pattern, options = {}) => { // shortcut. no need to expand. return [pattern]; } - return (0, brace_expansion_1.expand)(pattern, { max: options.braceExpandMax }); + // brace-expansion turns each escaped backslash '\\' into a single '\', + // which then escapes the next character instead, and can turn an + // escaped magic character (for example '\\\*') into a live one. + // Double every pair, so an escaped backslash comes back out still + // escaped. The parity of each run of backslashes is unchanged. + let p = pattern.replace(/\\\\/g, '\\\\\\\\'); + // brace-expansion does not know about [...] classes. In + // windowsPathsNoEscape mode, escape() writes a literal brace as '[{]' + // or '[}]'. Escape the brace for brace-expansion, which removes that + // backslash again, leaving '[{]' or '[}]'. + if (options.windowsPathsNoEscape || options[AWE_KEY] === false) { + p = p.replace(/\[([{}])\]/g, '[\\$1]'); + } + return (0, brace_expansion_1.expand)(p, { max: options.braceExpandMax }); }; exports.braceExpand = braceExpand; exports.minimatch.braceExpand = exports.braceExpand; -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); -exports.makeRe = makeRe; -exports.minimatch.makeRe = exports.makeRe; +// A numeric range with at least this many values is matched as one +// pattern portion, rather than expanded. For a glob walk, that is +// one directory read, in place of a stat for each value. +const RANGE_MIN = 100; +// a {lo..hi} range that is not escaped, and not a ${...} variable +const rangeRe = /(? { + const stack = []; + for (let i = 0; i < portion.length; i++) { + const c = portion.charAt(i); + if (c === '\\') { + i++; + } + else if (c === mark) { + if (stack.some(t => t !== '@' && t !== '?')) + return true; + } + else if (portion.charAt(i + 1) === '(' && '!?+*@'.includes(c)) { + stack.push(c); + i++; + } + else if (c === ')') { + stack.pop(); + } + } + return false; +}; const match = (list, pattern, options = {}) => { const mm = new Minimatch(pattern, options); list = list.filter(f => mm.match(f)); @@ -182,9 +306,228 @@ const match = (list, pattern, options = {}) => { }; exports.match = match; exports.minimatch.match = exports.match; -// replace stuff like \* with * const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; -const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +// Index of the `]` that closes the class that starts at `start`, +// or -1 if it is not closed. Posix classes such as `[:alpha:]` are +// not skipped, so this can find a `]` before the real end. That +// only makes a class look less like a literal. +const classEnd = (pattern, start) => { + let i = start + 1; + if (pattern.charAt(i) === '!' || pattern.charAt(i) === '^') + i++; + let sawStart = false; + for (; i < pattern.length; i++) { + const c = pattern.charAt(i); + if (c === ']' && sawStart) + return i; + sawStart = true; + if (c === '\\') + i++; + } + return -1; +}; +// If a path portion pattern has no magic, return the string it +// matches. Otherwise, return undefined. This can report magic for +// a pattern that is in fact literal (eg, `[]`), but never the +// reverse, so a string result is always safe to compare directly. +const literal = (pattern, noext) => { + if (!noext && (pattern === '+()' || pattern === '@()')) + return pattern; + let lit = ''; + for (let i = 0; i < pattern.length; i++) { + const c = pattern.charAt(i); + if (c === '\\') { + // a trailing \ is a literal \ + lit += pattern.charAt(++i) || c; + } + else if (c === '*' || c === '?') { + return undefined; + } + else if (c === '[') { + const close = classEnd(pattern, i); + if (close === -1) { + // not closed, so the [ is a literal + lit += c; + continue; + } + // a class of one char, such as `[*]` or `[\b]`, is a literal + let body = pattern.slice(i + 1, close); + if (body.startsWith('\\')) + body = body.slice(1); + if ([...body].length !== 1 || '!^'.includes(pattern.charAt(i + 1))) { + return undefined; + } + lit += body; + i = close; + } + else if (!noext && + '+@!'.includes(c) && + pattern.charAt(i + 1) === '(' && + pattern.includes(')', i + 2)) { + return undefined; + } + else { + lit += c; + } + } + return lit; +}; +// The matching engine compiles and walks extglobs recursively, so a +// path portion with very many extglobs (nested, such as `*(*(*(a)))`, +// or in a row, such as `?(a)?(a)?(a)`) can exhaust the call stack. +// Portions with more than this many extglobs are rejected. +const MAX_EXTGLOBS = 256; +// The number of extglob openers, such as `*(`, in a path portion +// pattern. Chars in a class are counted too, so this can be more than +// the number of extglobs, but never less. +const extglobCount = (pattern) => { + let n = 0; + for (let i = 0; i < pattern.length - 1; i++) { + const c = pattern.charAt(i); + if (c === '\\') { + i++; + } + else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') { + n++; + i++; + } + } + return n; +}; +const assertValidExtglobs = (pattern) => { + if (extglobCount(pattern) > MAX_EXTGLOBS) { + throw new TypeError('pattern has too many extglobs'); + } +}; +// True if the portion pattern has the same meaning as an alternative +// inside `@(...)`. It must not have a `|` or `)` that is not in a +// closed extglob (those are literal at the top level), an extglob +// that is not closed (the `)` of the `@(...)` would close it), or a +// trailing `\` (it would escape the next `|`). A pattern that is +// only an empty extglob, such as `?()`, is literal on its own, but +// not in `@(...)`. Posix classes such as `[:alpha:]` can hide a `]` +// from classEnd, so patterns with them are not merged. +const extSafe = (pattern) => { + if (/^[?*+@]\(\)$/.test(pattern) || pattern.includes('[:')) + return false; + let depth = 0; + for (let i = 0; i < pattern.length; i++) { + const c = pattern.charAt(i); + if (c === '\\') { + if (++i === pattern.length) + return false; + } + else if (c === '[') { + const close = classEnd(pattern, i); + if (close !== -1) + i = close; + } + else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') { + depth++; + i++; + } + else if (c === ')') { + if (!depth--) + return false; + } + else if (c === '|' && !depth) { + return false; + } + } + return !depth; +}; +// The last path that Minimatch#match split, and its parts. A path is +// often tested against many patterns in a row (such as a list of +// ignore patterns), so this saves splitting it again. The parts are +// never changed, so they can be shared. +let lastSplit; +// The last path that Minimatch#match checked before splitting it. If +// the same path is checked again, it is being tested against many +// patterns, so it is split and the parts are kept for the others. +let lastChecked; +// true if a pattern portion that is not ** matches a path portion. +// An empty path portion only matches an empty pattern portion. A path +// portion never has a `/`, so the Matcher does not need to check it. +const portionMatch = (p, f) => typeof p === 'string' ? f === p : f !== '' && p.testUnchecked(f); +// Where the last portion of a row matches in a path: the start of the +// last portion of the path, or of the one before a trailing `/`. -1 if +// it matches neither. +const endIndex = (p, last, lastStart, prev, prevStart) => portionMatch(p, last) ? lastStart + : prev !== undefined && portionMatch(p, prev) ? prevStart + : -1; +const isDots = (p) => p === '.' || p === '..'; +// a Windows drive letter portion, like `c:` +const isDrive = (p) => typeof p === 'string' && /^[a-z]:$/i.test(p); +// true for the `UNC` portion of a long UNC root, //?/UNC/host/share +const isLongUNC = (p) => typeof p === 'string' && /^unc$/i.test(p); +// The index of the host in a row or split path that starts with a +// Windows UNC root: 2 for `//host/share`, and 4 for +// `//?/UNC/host/share`. Otherwise -1. `//?/c:` is not one. +const uncHost = (p) => { + if (p[0] !== '' || p[1] !== '') + return -1; + const h = p[2] !== '?' ? 2 + : isLongUNC(p[3]) ? 4 + : -1; + const host = p[h]; + const share = p[h + 1]; + return (h !== -1 && + host !== undefined && + host !== '' && + host !== exports.GLOBSTAR && + share !== undefined && + share !== '' && + share !== exports.GLOBSTAR) ? + h + : -1; +}; +// true if ** can walk the path portion: not `.` or `..`, and not a +// dotfile unless `dot` is set +const walkable = (p, dot) => !isDots(p) && (dot || !p.startsWith('.')); +// True if a portion of the path from `start` to `end` can not be +// walked by **: one that starts with `.`, or with `dot`, one that is +// `.` or `..`. `start` is the start of a portion, and `end` is the end +// of the path, or just after a separator. +const dotPortion = (f, start, end, dot, sep) => { + for (let k = start; k < end;) { + if (f.charCodeAt(k) === 46) { + if (!dot) + return true; + const n = f.charCodeAt(k + 1) === 46 ? k + 2 : k + 1; + if (n >= end || isSep(f.charCodeAt(n), sep)) + return true; + } + // the start of the next portion, after any run of separators + const s = nextSep(f, k, sep); + if (s === -1) + return false; + k = s + 1; + while (k < end && isSep(f.charCodeAt(k), sep)) + k++; + } + return false; +}; +const isSep = (c, sep) => sep === '/' ? c === 47 + : sep === '\\' ? c === 92 + : c === 47 || c === 92; +// the index of the first separator at or after `from`, or -1 +const nextSep = (f, from, sep) => { + if (sep !== 'both') + return f.indexOf(sep, from); + const s = f.indexOf('/', from); + const b = f.indexOf('\\', from); + return (s === -1 ? b + : b === -1 ? s + : Math.min(s, b)); +}; +// the index of the last separator at or before `from`, or -1 +const lastSep = (f, from, sep) => sep !== 'both' ? + f.lastIndexOf(sep, from) + : Math.max(f.lastIndexOf('/', from), f.lastIndexOf('\\', from)); +// What parse() returns in place of a Matcher while make() builds and +// merges the rows. Most of the Matchers in rows that are merged would +// never be used, so they are only made for the rows that are left. +const PENDING = {}; class Minimatch { options; set; @@ -203,24 +546,44 @@ class Minimatch { platform; windowsNoMagicRoot; maxGlobstarRecursion; - regexp; + // the path can be checked against the last portion, and the string + // portions, of each row before it is split. See #canMatch. + #endCheck; + #literalCheck; + // level 2 resolves `.` and `..` portions in the path + #level2; + // the unicode normalization form, if any + #form; + // the string portions of each row in the set + #literals = []; + // the rows that #canMatch can match without splitting the path + #shapes = []; + // the rows whose last portion can be checked against the path's + #endRows = []; + // brace expansion can make the same portion in many rows, so they + // share one Matcher, and the states that it caches + #matchers = new Map(); + // parse() returns PENDING in place of a Matcher + #pending = false; + // the char that marks numeric ranges in globSet, if any + #rangeMark; + // the GlobstarParts of each pattern row, by start index and partial + #globstarParts = new WeakMap(); constructor(pattern, options = {}) { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); options = options || {}; this.options = options; - this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200; + this.maxGlobstarRecursion = + options.maxGlobstarRecursion ?? DEFAULT_GLOB_STAR_RECURSION_MAX; this.pattern = pattern; this.platform = options.platform || defaultPlatform; this.isWindows = this.platform === 'win32'; - // avoid the annoying deprecation flag lol - const awe = ('allowWindow' + 'sEscape'); this.windowsPathsNoEscape = - !!options.windowsPathsNoEscape || options[awe] === false; + !!options.windowsPathsNoEscape || options[AWE_KEY] === false; if (this.windowsPathsNoEscape) { this.pattern = this.pattern.replace(/\\/g, '/'); } this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; - this.regexp = null; this.negate = false; this.nonegate = !!options.nonegate; this.comment = false; @@ -234,8 +597,81 @@ class Minimatch { this.globSet = []; this.globParts = []; this.set = []; - // make the set of regexps etc. + this.#endCheck = !this.preserveMultipleSlashes; + this.#level2 = (options.optimizationLevel ?? 1) >= 2; + const n = options.normalize; + this.#form = n === true ? 'NFC' : n || undefined; + // make the set of Matchers etc. this.make(); + // On Windows, the portions of a row up to its drive letter or UNC + // share are skipped or compared without case, if the path has one + // too. So the checks only use the portions after it. + const drives = this.set.map(row => this.#rootIndex(row)); + this.#endRows = this.set.map((row, r) => this.#endCheck && row.length - 1 > drives[r]); + // with the end check, the last portion is already checked + this.#literals = this.set.map((row, r) => { + const end = this.#endRows[r] ? row.length - 1 : row.length; + const lits = row + .slice(drives[r] + 1, end) + .filter((p) => typeof p === 'string' && !!p); + return [...new Set(lits)]; + }); + this.#literalCheck = this.#literals.some(l => l.length); + this.#shapes = this.set.map((row, r) => { + const [p0, p1, p2] = row; + if (this.#endRows[r] && row.length === 2) { + if (p0 === exports.GLOBSTAR && p1 !== exports.GLOBSTAR) + return 'tail'; + } + // the basename of a path that is split on / is its last portion, + // or the one before a trailing /, the same as the end check + if (this.#endRows[r] && + options.matchBase && + row.length === 1 && + p0 !== exports.GLOBSTAR && + p0 !== '') { + return 'base'; + } + // the portion must not be a root, or '', which can be a + // different portion on Windows (where //x paths get an extra '') + if (!this.#endCheck || drives[r] !== -1) + return undefined; + if (row.length === 3 && + p0 === exports.GLOBSTAR && + p2 === exports.GLOBSTAR && + p1 !== exports.GLOBSTAR && + p1 !== '' && + // the portion between is only matched below this limit + this.maxGlobstarRecursion > 0) { + return 'mid'; + } + if (row.length === 2 && + p1 === exports.GLOBSTAR && + p0 !== exports.GLOBSTAR && + p0 !== '') { + return 'head'; + } + return undefined; + }); + } + // a string portion of a pattern, normalized if the option is set + #norm(p) { + return this.#form ? p.normalize(this.#form) : p; + } + // On Windows, the index of the last root portion of a row, as + // #matchRow finds it: 0 for `c:/...`, 3 for `//?/c:/...` and + // `//host/share/...`, and 5 for `//?/UNC/host/share/...`. Otherwise + // -1. + #rootIndex(row) { + if (!this.isWindows) + return -1; + if (isDrive(row[0])) + return 0; + const uncDrive = row[0] === '' && row[1] === '' && row[2] === '?' && isDrive(row[3]); + if (uncDrive) + return 3; + const h = uncHost(row); + return h === -1 ? -1 : h + 1; } hasMagic() { if (this.options.magicalBraces && this.set.length > 1) { @@ -249,7 +685,6 @@ class Minimatch { } return false; } - debug(..._) { } make() { const pattern = this.pattern; const options = this.options; @@ -265,46 +700,45 @@ class Minimatch { // step 1: figure out negation, etc. this.parseNegate(); // step 2: expand braces - this.globSet = [...new Set(this.braceExpand())]; - if (options.debug) { - //oxlint-disable-next-line no-console - this.debug = (...args) => console.error(...args); - } - this.debug(this.pattern, this.globSet); + this.globSet = [...new Set(this.#expandBraces())]; // step 3: now we have a set, so turn each one into a series of // path-portion matching patterns. - // These will be regexps, except in the case of "**", which is + // These will be Matchers, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters // // First, we preprocess to make the glob pattern sets a bit simpler // and deduped. There are some perf-killing patterns that can cause // problems with a glob walk, but we can simplify them down a bit. - const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); + const rawGlobParts = this.globSet.map(s => this.#slashSplit(s)); this.globParts = this.preprocess(rawGlobParts); - this.debug(this.pattern, this.globParts); - // glob --> regexps + // glob --> Matchers + this.#pending = true; let set = this.globParts.map((s, _, __) => { if (this.isWindows && this.windowsNoMagicRoot) { - // check if it's a drive or unc path. + // check if it's a drive or unc path. The root of a long UNC + // path, //?/UNC/host/share, is 6 portions. + const n = s[2] === '?' && isLongUNC(s[3]) ? 6 : 4; const isUNC = s[0] === '' && s[1] === '' && (s[2] === '?' || !globMagic.test(s[2])) && - !globMagic.test(s[3]); + s.slice(3, n).every(p => !globMagic.test(p)); const isDrive = /^[a-z]:/i.test(s[0]); if (isUNC) { return [ - ...s.slice(0, 4), - ...s.slice(4).map(ss => this.parse(ss)), + ...s.slice(0, n).map(p => this.#norm(p)), + ...s.slice(n).map(ss => this.parse(ss)), ]; } else if (isDrive) { - return [s[0], ...s.slice(1).map(ss => this.parse(ss))]; + return [ + this.#norm(s[0]), + ...s.slice(1).map(ss => this.parse(ss)), + ]; } } return s.map(ss => this.parse(ss)); }); - this.debug(this.pattern, set); // filter out everything that didn't compile properly. this.set = set.filter(s => s.indexOf(false) === -1); // do not treat the ? in UNC paths as magic @@ -314,13 +748,135 @@ class Minimatch { if (p[0] === '' && p[1] === '' && this.globParts[i][2] === '?' && - typeof p[3] === 'string' && - /^[a-z]:$/i.test(p[3])) { + (isDrive(p[3]) || isLongUNC(this.globParts[i][3]))) { + if (isLongUNC(this.globParts[i][3])) + p[3] = 'UNC'; p[2] = '?'; } } } - this.debug(this.pattern, this.set); + // with noext, `@(...)` would be literal + if (!options.noext) + this.mergeRows(); + this.#pending = false; + this.set.forEach((row, i) => { + for (let k = 0; k < row.length; k++) { + if (row[k] === PENDING) { + row[k] = this.parse(this.globParts[i][k]); + } + } + }); + } + // Merge rows that only differ in one portion, where each of them + // is a Matcher, into one row that matches any of them with + // `@(a|b|...)`. Then a path is only walked once for all of them, + // for example with `**/*.{js,ts}`. + mergeRows() { + let merged = true; + while (merged) { + merged = false; + // a single row cannot be merged with anything + if (this.set.length < 2) + return; + let keys = this.#mergeKeys(); + const len = Math.max(0, ...this.set.map(r => r.length)); + for (let k = 0; k < len; k++) { + // the rows that are the same other than at portion k, keyed + // by the ids of the parts before k and the parts after k, + // which are at most the number of rows + const groups = new Map(); + const R = this.set.length + 1; + this.set.forEach((row, i) => { + if (!(row[k] instanceof nonrecursive_glob_match_1.Matcher || row[k] === PENDING) || + !extSafe(this.globParts[i][k])) { + return; + } + const { pre, suf } = keys[i]; + const key = pre[k] * R + suf[k + 1]; + const g = groups.get(key); + if (g) + g.push(i); + else + groups.set(key, [i]); + }); + const drop = new Set(); + for (const g of groups.values()) { + if (g.length < 2) + continue; + const [first, ...rest] = g; + const alts = g.map(i => this.globParts[i][k]); + const glob = `@(${alts.join('|')})`; + // merging is only an optimization, so leave the rows as they + // are if the merged portion would have too many extglobs + if (extglobCount(glob) > MAX_EXTGLOBS) + continue; + this.globParts[first][k] = glob; + this.set[first][k] = this.parse(glob); + for (const i of rest) + drop.add(i); + } + if (drop.size) { + merged = true; + this.set = this.set.filter((_, i) => !drop.has(i)); + this.globParts = this.globParts.filter((_, i) => !drop.has(i)); + // every merge drops a row, so this happens at most once per row + if (this.set.length < 2) + return; + keys = this.#mergeKeys(); + } + } + } + } + // For each row, number ids for its prefixes and suffixes, such that + // pre[k] identifies parts[0..k) and suf[k] identifies parts[k..n). + // Two rows are the same other than at portion k exactly when they + // have the same pre[k] and suf[k + 1]. This is linear in the size of + // the rows, where joining the whole row for every k was quadratic. + #mergeKeys() { + const partIds = new Map(); + const ids = this.globParts.map(parts => parts.map(s => { + let id = partIds.get(s); + if (id === undefined) + partIds.set(s, (id = partIds.size)); + return id; + })); + // ids are only compared at the same k, so they are numbered per + // portion, with 0 for the empty prefix or suffix. Then they are + // at most the number of rows, and id * P + part id is a safe + // integer key for any set that fits in memory. + const P = partIds.size; + const len = Math.max(0, ...ids.map(r => r.length)); + const keys = ids.map(r => ({ + pre: [0], + suf: new Array(r.length + 1).fill(0), + })); + for (let k = 0; k < len; k++) { + const m = new Map(); + ids.forEach((r, i) => { + if (k >= r.length) + return; + const { pre } = keys[i]; + const key = pre[k] * P + r[k]; + let id = m.get(key); + if (id === undefined) + m.set(key, (id = m.size + 1)); + pre.push(id); + }); + } + for (let k = len - 1; k >= 0; k--) { + const m = new Map(); + ids.forEach((r, i) => { + if (k >= r.length) + return; + const { suf } = keys[i]; + const key = suf[k + 1] * P + r[k]; + let id = m.get(key); + if (id === undefined) + m.set(key, (id = m.size + 1)); + suf[k] = id; + }); + } + return keys; } // various transforms to equivalent pattern sets that are // faster to process in a filesystem walk. The goal is to @@ -373,13 +929,19 @@ class Minimatch { // get rid of adjascent ** and resolve .. portions levelOneOptimize(globParts) { return globParts.map(parts => { + // .. can not remove the root of a Windows path + const root = this.#rootIndex(parts) + 1; parts = parts.reduce((set, part) => { const prev = set[set.length - 1]; if (part === '**' && prev === '**') { return set; } if (part === '..') { - if (prev && prev !== '..' && prev !== '.' && prev !== '**') { + if (set.length > root && + prev && + prev !== '..' && + prev !== '.' && + prev !== '**') { set.pop(); return set; } @@ -390,10 +952,214 @@ class Minimatch { return parts.length === 0 ? [''] : parts; }); } - levelTwoFileOptimize(parts) { - if (!Array.isArray(parts)) { - parts = this.slashSplit(parts); + // Check the path against each row before it is split. 'no' if no + // row can match, so it does not need to be split. 'yes' if a row of + // `**` and one more portion matches. 'maybe' if it must be split to + // know. None of this applies with partial, where the path can end + // before the row does. + // + // On Windows, `\` is a separator in the path too, and the portions of + // a row up to its drive letter or UNC share are not checked (see + // #rootIndex). + // + // Each string portion of a row must be a portion of the path, so the + // path must contain it. Level 2 can only take portions out of the + // path, so this is still true then. + // + // The last portion of a row must match the last portion of the path, + // or the one before a trailing `/` (as a/* and a/**/* match a/b/). + // This does not apply to rows that end in **, rows that end in a + // root, or preserveMultipleSlashes (which can leave more + // than one '' at the end). At level 2, it does not apply if that + // portion is `.` or `..`, which can be + // resolved away. Level 2 only takes other portions out of the + // middle of the path. + // + // A row of `**/x` then matches if the ** can walk the portions + // before the one that x matches, the same as #matchGlobstar. At + // level 2, this is only known if none of them are `.` or `..`, so + // that the path does not change when it is resolved. + #canMatch(f) { + const sep = !this.isWindows || !f.includes('\\') ? '/' + : f.includes('/') ? 'both' + : '\\'; + // the portions that f.split(/\/+/) would end with, and where they + // start in f, found when a row needs them. `ends` is 0 until they + // are found, then 1, or -1 if they can not be used. + let ends = this.#endCheck ? 0 : -1; + let last = ''; + let lastStart = 0; + let prev; + let prevStart = 0; + const dot = !!this.options.dot; + // A string compare is cheaper than includes(), and a Matcher test + // costs more, so the cheaper check goes first. + ROWS: for (let r = 0; r < this.set.length; r++) { + const row = this.set[r]; + const p = row[row.length - 1]; + let end = ends !== -1 && this.#endRows[r] && p !== exports.GLOBSTAR; + if (end && ends === 0) { + const i = lastSep(f, f.length, sep); + lastStart = i + 1; + last = f.slice(lastStart); + if (last === '' && i >= 0) { + let j = i; + while (j > 0 && isSep(f.charCodeAt(j - 1), sep)) + j--; + prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep) + 1; + prev = f.slice(prevStart, j); + } + const resolves = this.#level2 && + (isDots(last) || + (last === '' && prev !== undefined && isDots(prev))); + ends = resolves ? -1 : 1; + end = !resolves; + } + let tailStart = -1; + if (end && typeof p === 'string') { + tailStart = endIndex(p, last, lastStart, prev, prevStart); + if (tailStart === -1) + continue; + } + if (this.#literalCheck) { + for (const l of this.#literals[r]) { + if (!f.includes(l)) + continue ROWS; + } + } + if (end && typeof p === 'object') { + tailStart = endIndex(p, last, lastStart, prev, prevStart); + if (tailStart === -1) + continue; + } + const shape = this.#shapes[r]; + if (shape === 'base' && end) + return 'yes'; + if (shape === 'tail' && end) { + if (this.#level2 && dotPortion(f, 0, tailStart, true, sep)) { + return 'maybe'; + } + if (!dotPortion(f, 0, tailStart, dot, sep)) + return 'yes'; + continue; + } + if (shape === 'mid' || shape === 'head') { + const m = this.#walk(f, row, shape === 'head', dot, sep); + if (m !== 'no') + return m; + continue; + } + return 'maybe'; + } + return 'no'; + } + // Match a row of a known shape against the split path, the same as + // #matchGlobstar and #matchGlobStarBodySections do. None of these + // rows have a drive letter, so they start at the first portion. + #matchShape(file, row, shape) { + const dot = !!this.options.dot; + const n = file.length; + if (shape === 'head') { + // x, then at least one portion that ** can walk + if (n < 2 || !portionMatch(row[0], file[0])) { + return false; + } + for (let i = 1; i < n; i++) + if (!walkable(file[i], dot)) + return false; + return true; + } + const x = row[1]; + if (shape === 'tail') { + // x is the last portion, or the one before a trailing '' + let t = n - 1; + if (!portionMatch(x, file[t])) { + if (file[t] !== '' || n === 1 || !portionMatch(x, file[--t])) { + return false; + } + } + for (let i = 0; i < t; i++) + if (!walkable(file[i], dot)) + return false; + return true; } + // mid: the first x that ** can walk to, with a portion after it, + // and ** can walk all of those + for (let k = 0; k < n; k++) { + if (portionMatch(x, file[k]) && k + 1 < n) { + let i = k + 1; + while (i < n && walkable(file[i], dot)) + i++; + if (i === n) + return true; + } + if (!walkable(file[k], dot)) + return false; + } + return false; + } + // Match a row of `**/x/**` or `x/**` against the path, the same as + // #matchGlobstar and #matchGlobStarBodySections do once it is split. + // x must match a portion (the first one, for `x/**`), the ** before + // it must be able to walk the portions before that one, and there + // must be a portion after it, which the ** after it can walk. At + // level 2, this is only known if no portion is `.` or `..`. + #walk(f, row, head, dot, sep) { + if (this.#level2 && dotPortion(f, 0, f.length, true, sep)) + return 'maybe'; + const x = row[head ? 0 : 1]; + // the last portion has none after it, so it can not be x + let s = 0; + for (let e = nextSep(f, s, sep); e !== -1; e = nextSep(f, s, sep)) { + // the start of the next portion + let next = e + 1; + while (next < f.length && isSep(f.charCodeAt(next), sep)) + next++; + const hit = typeof x === 'string' ? + e - s === x.length && f.startsWith(x, s) + : e > s && x.testUnchecked(f.slice(s, e)); + if (hit && !dotPortion(f, next, f.length, dot, sep)) + return 'yes'; + if (head || dotPortion(f, s, next, dot, sep)) + return 'no'; + s = next; + } + return 'no'; + } + // the last split, if it was the same path with the same split + // settings + #cachedSplit(f) { + const last = lastSplit; + return (last?.f === f && + last.isWindows === this.isWindows && + last.preserveMultipleSlashes === this.preserveMultipleSlashes && + last.normalize === this.#form) ? + last + : undefined; + } + // split a path for match(), and keep the parts for the next call + #split(f) { + const { isWindows, preserveMultipleSlashes } = this; + // windows: need to use /, not \ + let parts = this.#slashSplit(isWindows ? f.split('\\').join('/') : f); + // normalize each portion, so that a char that normalizes to `/` + // does not make a new portion + const normalize = this.#form; + if (normalize) + parts = parts.map(p => p.normalize(normalize)); + lastSplit = { + f, + isWindows, + preserveMultipleSlashes, + normalize, + parts, + }; + return lastSplit; + } + // resolve `.` and `..` portions of a path, for level 2 + #levelTwoFileOptimize(file) { + // work on a copy, so that the cached parts do not change + const parts = [...file]; let didSomething = false; do { didSomething = false; @@ -418,17 +1184,15 @@ class Minimatch { } } //

/

/../ ->

/
-            let dd = 0;
+            // .. can not remove the root of a Windows path
+            const root = this.#rootIndex(parts) + 1;
+            let dd = root;
             while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                 const p = parts[dd - 1];
-                if (p &&
-                    p !== '.' &&
-                    p !== '..' &&
-                    p !== '**' &&
-                    !(this.isWindows && /^[a-z]:$/i.test(p))) {
+                if (p && p !== '.' && p !== '..' && p !== '**') {
                     didSomething = true;
                     parts.splice(dd - 1, 2);
-                    dd -= 2;
+                    dd = Math.max(dd - 2, root);
                 }
             }
         } while (didSomething);
@@ -453,6 +1217,13 @@ class Minimatch {
     // **/*/ -> */**/ <== not valid because ** doesn't follow
     // this WOULD be allowed if ** did follow symlinks, or * didn't
     firstPhasePreProcess(globParts) {
+        // each **/.. split doubles the patterns, and adds a copy of the
+        // whole pattern. Throw if either gets too large. A partial split
+        // would match some paths and not others, depending on which rows
+        // the pass reached first.
+        const { braceExpandMax = DEFAULT_BRACE_EXPAND_MAX } = this.options;
+        let splitCells = 0;
+        const maxSplitCells = 1_000_000;
         let didSomething = false;
         do {
             didSomething = false;
@@ -483,11 +1254,18 @@ class Minimatch {
                         p2 === '..') {
                         continue;
                     }
+                    // Check before changing parts or allocating the new row.
+                    const addedCells = parts.length - 1;
+                    if (globParts.length >= braceExpandMax ||
+                        splitCells + addedCells > maxSplitCells) {
+                        throw new RangeError(`optimizationLevel 2: too many patterns from '**/..'`);
+                    }
                     didSomething = true;
                     // edit parts in place, and push the new one
                     parts.splice(gs, 1);
                     const other = parts.slice(0);
                     other[gs] = '**';
+                    splitCells += addedCells;
                     globParts.push(other);
                     gs--;
                 }
@@ -512,7 +1290,9 @@ class Minimatch {
                     }
                 }
                 // 
/

/../ ->

/
-                let dd = 0;
+                // .. can not remove the root of a Windows path
+                const root = this.#rootIndex(parts) + 1;
+                let dd = root;
                 while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                     const p = parts[dd - 1];
                     if (p && p !== '.' && p !== '..' && p !== '**') {
@@ -522,7 +1302,7 @@ class Minimatch {
                         parts.splice(dd - 1, 2, ...splin);
                         if (parts.length === 0)
                             parts.push('');
-                        dd -= 2;
+                        dd = Math.max(dd - 2, root);
                     }
                 }
             }
@@ -530,73 +1310,59 @@ class Minimatch {
         return globParts;
     }
     // second phase: multi-pattern dedupes
-    // {
/*/,
/

/} ->

/*/
     // {
/,
/} -> 
/
-    // {
/**/,
/} -> 
/**/
-    //
-    // {
/**/,
/**/

/} ->

/**/
-    // ^-- not valid because ** doens't follow symlinks
+    // {
/*/,
/

/} ->

/*/
     secondPhasePreProcess(globParts) {
-        for (let i = 0; i < globParts.length - 1; i++) {
-            for (let j = i + 1; j < globParts.length; j++) {
-                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
-                if (matched) {
-                    globParts[i] = [];
-                    globParts[j] = matched;
-                    break;
-                }
+        const keys = new Set();
+        const rows = globParts.filter(parts => {
+            const key = parts.join('/');
+            if (keys.has(key))
+                return false;
+            keys.add(key);
+            return true;
+        });
+        // A row is covered by another row that has `*` at some positions,
+        // and is the same at all others. Collect each distinct set of `*`
+        // positions, then look up each row with `*` put at those positions.
+        const stars = new Map();
+        for (const parts of rows) {
+            const s = [];
+            for (let i = 0; i < parts.length; i++) {
+                if (parts[i] === '*')
+                    s.push(i);
             }
+            if (s.length)
+                stars.set(s.join(','), s);
         }
-        return globParts.filter(gs => gs.length);
-    }
-    partsMatch(a, b, emptyGSMatch = false) {
-        let ai = 0;
-        let bi = 0;
-        let result = [];
-        let which = '';
-        while (ai < a.length && bi < b.length) {
-            if (a[ai] === b[bi]) {
-                result.push(which === 'b' ? b[bi] : a[ai]);
-                ai++;
-                bi++;
-            }
-            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
-                result.push(a[ai]);
-                ai++;
-            }
-            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
-                result.push(b[bi]);
-                bi++;
-            }
-            else if (a[ai] === '*' &&
-                b[bi] &&
-                (this.options.dot || !b[bi].startsWith('.')) &&
-                b[bi] !== '**') {
-                if (which === 'b')
-                    return false;
-                which = 'a';
-                result.push(a[ai]);
-                ai++;
-                bi++;
-            }
-            else if (b[bi] === '*' &&
-                a[ai] &&
-                (this.options.dot || !a[ai].startsWith('.')) &&
-                a[ai] !== '**') {
-                if (which === 'a')
+        // Each row is checked against each set of `*` positions, so skip
+        // this if there are too many. The patterns match the same paths
+        // either way.
+        if (!stars.size || rows.length * stars.size > 100_000)
+            return rows;
+        const { dot } = this.options;
+        return rows.filter(parts => {
+            for (const s of stars.values()) {
+                if (s[s.length - 1] >= parts.length)
+                    continue;
+                const c = [...parts];
+                let ok = true;
+                let changed = false;
+                for (const i of s) {
+                    const p = parts[i];
+                    if (p === '*')
+                        continue;
+                    if (!p || p === '**' || (!dot && p.startsWith('.'))) {
+                        ok = false;
+                        break;
+                    }
+                    c[i] = '*';
+                    changed = true;
+                }
+                if (ok && changed && keys.has(c.join('/')))
                     return false;
-                which = 'b';
-                result.push(b[bi]);
-                ai++;
-                bi++;
             }
-            else {
-                return false;
-            }
-        }
-        // if we fall out of the loop, it means they two are identical
-        // as long as their lengths match
-        return a.length === b.length && result;
+            return true;
+        });
     }
     parseNegate() {
         if (this.nonegate)
@@ -612,18 +1378,36 @@ class Minimatch {
             this.pattern = pattern.slice(negateOffset);
         this.negate = negate;
     }
-    // set partial to true to test if, for example,
-    // "/a/b" matches the start of "/*/b/*/d"
-    // Partial means, if you run out of file before you run
-    // out of pattern, then that's fine, as long as all
-    // the parts match.
-    matchOne(file, pattern, partial = false) {
+    // Match the parts of a path against one row of the set. `resolved`
+    // is the parts after level 2 resolves `.` and `..` in them, or the
+    // same parts below level 2. Set partial to true to test if, for
+    // example, "/a/b" matches the start of "/*/b/*/d". Partial means, if
+    // you run out of file before you run out of pattern, then that's
+    // fine, as long as all the parts match.
+    #matchRow(file, resolved, pattern, partial) {
         let fileStartIndex = 0;
         let patternStartIndex = 0;
-        // UNC paths like //?/X:/... can match X:/... and vice versa
-        // Drive letters in absolute drive or unc paths are always compared
-        // case-insensitively.
-        if (this.isWindows) {
+        // UNC paths like //?/X:/... can match X:/... and vice versa, and
+        // //?/UNC/host/share/... can match //host/share/... and vice versa.
+        // Drive letters in absolute drive or unc paths, and the host and
+        // share of UNC paths, are always compared case-insensitively.
+        const fh = this.isWindows ? uncHost(resolved) : -1;
+        const ph = fh === -1 ? -1 : uncHost(pattern);
+        if (ph !== -1) {
+            const host = pattern[ph];
+            const share = pattern[ph + 1];
+            if (typeof host !== 'string' || typeof share !== 'string') {
+                // a host or share with magic is matched as usual
+                fileStartIndex = fh;
+                patternStartIndex = ph;
+            }
+            else if (resolved[fh].toLowerCase() === host.toLowerCase() &&
+                resolved[fh + 1].toLowerCase() === share.toLowerCase()) {
+                fileStartIndex = fh + 2;
+                patternStartIndex = ph + 2;
+            }
+        }
+        else if (this.isWindows) {
             const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
             const fileUNC = !fileDrive &&
                 file[0] === '' &&
@@ -648,47 +1432,27 @@ class Minimatch {
                     file[fdi],
                     pattern[pdi],
                 ];
-                // start matching at the drive letter index of each
+                // the drives match, so start matching after them
                 if (fd.toLowerCase() === pd.toLowerCase()) {
-                    pattern[pdi] = fd;
-                    patternStartIndex = pdi;
-                    fileStartIndex = fdi;
+                    patternStartIndex = pdi + 1;
+                    fileStartIndex = fdi + 1;
                 }
             }
         }
-        // resolve and reduce . and .. portions in the file as well.
-        // don't need to do the second phase, because it's only one string[]
-        const { optimizationLevel = 1 } = this.options;
-        if (optimizationLevel >= 2) {
-            file = this.levelTwoFileOptimize(file);
-        }
+        // the drive letters are found in the parts before level 2 resolves
+        // them, and the match uses the resolved parts
+        file = resolved;
         if (pattern.includes(exports.GLOBSTAR)) {
             return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
         }
         return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
     }
     #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
-        // split the pattern into head, tail, and middle of ** delimited parts
-        const firstgs = pattern.indexOf(exports.GLOBSTAR, patternIndex);
-        const lastgs = pattern.lastIndexOf(exports.GLOBSTAR);
-        // split the pattern up into globstar-delimited sections
-        // the tail has to be at the end, and the others just have
-        // to be found in order from the head.
-        const [head, body, tail] = partial ?
-            [
-                pattern.slice(patternIndex, firstgs),
-                pattern.slice(firstgs + 1),
-                [],
-            ]
-            : [
-                pattern.slice(patternIndex, firstgs),
-                pattern.slice(firstgs + 1, lastgs),
-                pattern.slice(lastgs + 1),
-            ];
+        const { head, body, tail, segments } = this.#getGlobstarParts(pattern, partial, patternIndex);
         // check the head, from the current file/pattern index.
         if (head.length) {
-            const fileHead = file.slice(fileIndex, fileIndex + head.length);
-            if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
+            const headEnd = fileIndex + head.length;
+            if (!this.#matchOne(file, head, partial, fileIndex, 0, headEnd)) {
                 return false;
             }
             fileIndex += head.length;
@@ -746,36 +1510,64 @@ class Minimatch {
         // now we know that there's one or more body sections, which can
         // be matched anywhere from the 0 index (because the head was pruned)
         // through to the length-fileTailMatch index.
-        // split the body up into sections, and note the minimum index it can
-        // be found at (start with the length of all previous segments)
-        // [section, before, after]
-        const bodySegments = [[[], 0]];
-        let currentBody = bodySegments[0];
+        return !!this.#matchGlobStarBodySections(file, segments, file.length - fileTailMatch, fileIndex, 0, partial, 0, !!fileTailMatch, new Set());
+    }
+    // Split the pattern into head, tail, and middle of ** delimited
+    // parts. The tail has to be at the end, and the others just have to
+    // be found in order from the head. These only depend on the pattern
+    // row, so they are kept for the next path.
+    #getGlobstarParts(pattern, partial, patternIndex) {
+        let byStart = this.#globstarParts.get(pattern);
+        if (!byStart) {
+            byStart = [];
+            this.#globstarParts.set(pattern, byStart);
+        }
+        const key = patternIndex * 2 + (partial ? 1 : 0);
+        const found = byStart[key];
+        if (found)
+            return found;
+        const firstgs = pattern.indexOf(exports.GLOBSTAR, patternIndex);
+        const lastgs = pattern.lastIndexOf(exports.GLOBSTAR);
+        const head = pattern.slice(patternIndex, firstgs);
+        const body = pattern.slice(firstgs + 1, partial ? undefined : lastgs);
+        const tail = partial ? [] : pattern.slice(lastgs + 1);
+        // split the body up into sections, and note the number of
+        // portions that must come after the start of each one
+        const segments = [[[], 0]];
+        let current = segments[0];
         let nonGsParts = 0;
         const nonGsPartsSums = [0];
         for (const b of body) {
             if (b === exports.GLOBSTAR) {
                 nonGsPartsSums.push(nonGsParts);
-                currentBody = [[], 0];
-                bodySegments.push(currentBody);
+                current = [[], 0];
+                segments.push(current);
             }
             else {
-                currentBody[0].push(b);
+                current[0].push(b);
                 nonGsParts++;
             }
         }
-        let i = bodySegments.length - 1;
-        const fileLength = file.length - fileTailMatch;
-        for (const b of bodySegments) {
-            b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
-        }
-        return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
+        // the portions in this section and the ones after it
+        segments.forEach((b, i) => {
+            b[1] = nonGsParts - nonGsPartsSums[i];
+        });
+        const parts = { head, body, tail, segments };
+        byStart[key] = parts;
+        return parts;
     }
     // return false for "nope, not matching"
     // return null for "not matching, cannot keep trying"
     #matchGlobStarBodySections(file, 
-    // pattern section, last possible position for it
-    bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
+    // pattern section, and the portions that it and the rest need
+    bodySegments, 
+    // the end of the file portions that the body can match
+    fileLength, fileIndex, bodyIndex, partial, globStarDepth, sawTail, 
+    // the places that a walk has already tried, as
+    // bodyIndex * (file.length + 1) + fileIndex. A walk from a place
+    // does the same no matter how it got there, and it only comes back
+    // if it found no match, so a walk that gets to one stops.
+    tried) {
         // take the first body segment, and walk from fileIndex to its "after"
         // value at the end
         // If it doesn't match at that position, we increment, until we hit
@@ -787,8 +1579,16 @@ class Minimatch {
         // can't possibly be a valid matching condition.
         const bs = bodySegments[bodyIndex];
         if (!bs) {
-            // just make sure that there's no bad dots
-            for (let i = fileIndex; i < file.length; i++) {
+            // with partial, the body is the rest of the pattern, so it
+            // matches if no portions are left, or only the '' of a trailing
+            // / (as a/* matches a/b/). A ** at the end walks them as its own
+            // empty section.
+            if (partial) {
+                return (fileIndex >= fileLength ||
+                    (fileIndex === fileLength - 1 && file[fileIndex] === ''));
+            }
+            // just make sure that there's no bad dots before the tail
+            for (let i = fileIndex; i < fileLength; i++) {
                 sawTail = true;
                 const f = file[i];
                 if (f === '.' ||
@@ -799,19 +1599,29 @@ class Minimatch {
             }
             return sawTail;
         }
-        // have a non-globstar body section to test
-        const [body, after] = bs;
+        // have a non-globstar body section to test, up to the last index
+        // where it can start
+        const [body, need] = bs;
+        // with partial, the path can end before the body does
+        const after = partial ? fileLength : fileLength - need;
         while (fileIndex <= after) {
-            const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
+            const key = bodyIndex * (file.length + 1) + fileIndex;
+            if (tried.has(key))
+                return false;
+            tried.add(key);
+            const m = this.#matchOne(file, body, partial, fileIndex, 0, fileIndex + body.length);
             // if limit exceeded, no match. intentional false negative,
             // acceptable break in correctness for security.
             if (m && globStarDepth < this.maxGlobstarRecursion) {
                 // match! see if the rest match. if so, we're done!
-                const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
+                const sub = this.#matchGlobStarBodySections(file, bodySegments, fileLength, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail, tried);
                 if (sub !== false) {
                     return sub;
                 }
             }
+            // the ** does not walk past the last place the body can start
+            if (fileIndex === after)
+                break;
             const f = file[fileIndex];
             if (f === '.' ||
                 f === '..' ||
@@ -823,21 +1633,20 @@ class Minimatch {
         // walked off. no point continuing
         return partial || null;
     }
-    #matchOne(file, pattern, partial, fileIndex, patternIndex) {
+    #matchOne(file, pattern, partial, fileIndex, patternIndex, 
+    // only match the file portions before this index
+    fileEnd = file.length) {
         let fi;
         let pi;
         let pl;
         let fl;
         for (fi = fileIndex,
             pi = patternIndex,
-            fl = file.length,
+            fl = Math.min(fileEnd, file.length),
             pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
-            this.debug('matchOne loop');
             let p = pattern[pi];
             let f = file[fi];
-            this.debug(pattern, p, f);
             // should be impossible.
-            // some invalid regexp stuff in the set.
             /* c8 ignore start */
             if (p === false || p === exports.GLOBSTAR) {
                 return false;
@@ -845,17 +1654,8 @@ class Minimatch {
             /* c8 ignore stop */
             // something other than **
             // non-magic patterns just have to match exactly
-            // patterns with magic have been turned into regexps.
-            let hit;
-            if (typeof p === 'string') {
-                hit = f === p;
-                this.debug('string match', p, f, hit);
-            }
-            else {
-                hit = p.test(f);
-                this.debug('pattern match', p, f, hit);
-            }
-            if (!hit)
+            // patterns with magic have been turned into Matchers.
+            if (!portionMatch(p, f))
                 return false;
         }
         // Note: ending in / means that we'll get a final ""
@@ -864,9 +1664,8 @@ class Minimatch {
         // If the file ends in /, then it can only match a
         // a pattern that ends in /, unless the pattern just
         // doesn't have any more for it. But, a/b/ should *not*
-        // match "a/b/*", even though "" matches against the
-        // [^/]*? pattern, except in partial mode, where it might
-        // simply not be reached yet.
+        // match "a/b/*", even though * can match "", except in
+        // partial mode, where it might simply not be reached yet.
         // However, a/b/ should still satisfy a/*
         // now either we fell off the end of the pattern, or we're done.
         if (fi === fl && pi === pl) {
@@ -897,6 +1696,49 @@ class Minimatch {
     braceExpand() {
         return (0, exports.braceExpand)(this.pattern, this.options);
     }
+    // Expand braces, except numeric ranges such as {0..999} with at
+    // least RANGE_MIN values. Each of those stays in its pattern as
+    // `0..999`, for the Matcher to test. If a range might
+    // be inside a [...] class, expand all of them instead.
+    #expandBraces() {
+        const { pattern } = this;
+        if (this.options.nobrace)
+            return this.braceExpand();
+        let code = 0xe000;
+        while (pattern.includes(String.fromCharCode(code))) {
+            if (++code > 0xf8ff)
+                return this.braceExpand();
+        }
+        const mark = String.fromCharCode(code);
+        let found = false;
+        const marked = pattern.replace(rangeRe, (m, lo, hi) => {
+            const a = Number(lo);
+            const b = Number(hi);
+            if (!Number.isSafeInteger(a) ||
+                !Number.isSafeInteger(b) ||
+                Math.abs(a - b) + 1 < RANGE_MIN) {
+                return m;
+            }
+            found = true;
+            return `${mark}${lo}..${hi}${mark}`;
+        });
+        if (!found)
+            return this.braceExpand();
+        const set = (0, exports.braceExpand)(marked, this.options);
+        for (const p of set) {
+            for (const portion of p.split('/')) {
+                const c = portion.indexOf('[');
+                if (c !== -1 && c < portion.lastIndexOf(mark)) {
+                    return this.braceExpand();
+                }
+                if (!this.options.noext && inRepeatOrNegExt(portion, mark)) {
+                    return this.braceExpand();
+                }
+            }
+        }
+        this.#rangeMark = mark;
+        return set;
+    }
     parse(pattern) {
         (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
         const options = this.options;
@@ -905,139 +1747,37 @@ class Minimatch {
             return exports.GLOBSTAR;
         if (pattern === '')
             return '';
-        // far and away, the most common glob pattern parts are
-        // *, *.*, and *.  Add a fast check method for those.
-        let m;
-        let fastTest = null;
-        if ((m = pattern.match(starRE))) {
-            fastTest = options.dot ? starTestDot : starTest;
-        }
-        else if ((m = pattern.match(starDotExtRE))) {
-            fastTest = (options.nocase ?
-                options.dot ?
-                    starDotExtTestNocaseDot
-                    : starDotExtTestNocase
-                : options.dot ? starDotExtTestDot
-                    : starDotExtTest)(m[1]);
-        }
-        else if ((m = pattern.match(qmarksRE))) {
-            fastTest = (options.nocase ?
-                options.dot ?
-                    qmarksTestNocaseDot
-                    : qmarksTestNocase
-                : options.dot ? qmarksTestDot
-                    : qmarksTest)(m);
-        }
-        else if ((m = pattern.match(starDotStarRE))) {
-            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
-        }
-        else if ((m = pattern.match(dotStarRE))) {
-            fastTest = dotStarTest;
-        }
-        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
-        if (fastTest && typeof re === 'object') {
-            // Avoids overriding in frozen environments
-            Reflect.defineProperty(re, 'test', { value: fastTest });
-        }
-        return re;
-    }
-    makeRe() {
-        if (this.regexp || this.regexp === false)
-            return this.regexp;
-        // at this point, this.set is a 2d array of partial
-        // pattern strings, or "**".
-        //
-        // It's better to use .match().  This function shouldn't
-        // be used, really, but it's pretty convenient sometimes,
-        // when you just want to work with a regex.
-        const set = this.set;
-        if (!set.length) {
-            this.regexp = false;
-            return this.regexp;
+        const { nocase, nocaseMagicOnly, noext = false, dot, normalize, } = options;
+        const rangeMark = this.#rangeMark;
+        const lit = rangeMark && pattern.includes(rangeMark) ?
+            undefined
+            : literal(pattern, noext);
+        // in nocase mode, a literal with cased chars still needs a
+        // Matcher, unless nocaseMagicOnly is set.
+        if (lit !== undefined &&
+            !(nocase &&
+                !nocaseMagicOnly &&
+                pattern.toUpperCase() !== pattern.toLowerCase())) {
+            return this.#norm(lit);
         }
-        const options = this.options;
-        const twoStar = options.noglobstar ? star
-            : options.dot ? twoStarDot
-                : twoStarNoDot;
-        const flags = new Set(options.nocase ? ['i'] : []);
-        // regexpify non-globstar patterns
-        // if ** is only item, then we just do one twoStar
-        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
-        // if ** is last, append (\/twoStar|) to previous
-        // if ** is in the middle, append (\/|\/twoStar\/) to previous
-        // then filter out GLOBSTAR symbols
-        let re = set
-            .map(pattern => {
-            const pp = pattern.map(p => {
-                if (p instanceof RegExp) {
-                    for (const f of p.flags.split(''))
-                        flags.add(f);
-                }
-                return (typeof p === 'string' ? regExpEscape(p)
-                    : p === exports.GLOBSTAR ? exports.GLOBSTAR
-                        : p._src);
+        if (this.#pending)
+            return PENDING;
+        let m = this.#matchers.get(pattern);
+        if (!m) {
+            if (!noext)
+                assertValidExtglobs(pattern);
+            m = new nonrecursive_glob_match_1.Matcher(pattern, {
+                nocase,
+                noext,
+                dot,
+                normalize,
+                ...(rangeMark && { rangeMark }),
             });
-            pp.forEach((p, i) => {
-                const next = pp[i + 1];
-                const prev = pp[i - 1];
-                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
-                    return;
-                }
-                if (prev === undefined) {
-                    if (next !== undefined && next !== exports.GLOBSTAR) {
-                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
-                    }
-                    else {
-                        pp[i] = twoStar;
-                    }
-                }
-                else if (next === undefined) {
-                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
-                }
-                else if (next !== exports.GLOBSTAR) {
-                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
-                    pp[i + 1] = exports.GLOBSTAR;
-                }
-            });
-            const filtered = pp.filter(p => p !== exports.GLOBSTAR);
-            // For partial matches, we need to make the pattern match
-            // any prefix of the full path. We do this by generating
-            // alternative patterns that match progressively longer prefixes.
-            if (this.partial && filtered.length >= 1) {
-                const prefixes = [];
-                for (let i = 1; i <= filtered.length; i++) {
-                    prefixes.push(filtered.slice(0, i).join('/'));
-                }
-                return '(?:' + prefixes.join('|') + ')';
-            }
-            return filtered.join('/');
-        })
-            .join('|');
-        // need to wrap in parens if we had more than one thing with |,
-        // otherwise only the first will be anchored to ^ and the last to $
-        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
-        // must match entire pattern
-        // ending in a * or ** will make it less strict.
-        re = '^' + open + re + close + '$';
-        // In partial mode, '/' should always match as it's a valid prefix for any pattern
-        if (this.partial) {
-            re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
-        }
-        // can match anything, as long as it's not this.
-        if (this.negate)
-            re = '^(?!' + re + ').+$';
-        try {
-            this.regexp = new RegExp(re, [...flags].join(''));
-            /* c8 ignore start */
+            this.#matchers.set(pattern, m);
         }
-        catch {
-            // should be impossible
-            this.regexp = false;
-        }
-        /* c8 ignore stop */
-        return this.regexp;
+        return m;
     }
-    slashSplit(p) {
+    #slashSplit(p) {
         // if p starts with // on windows, we preserve that
         // so that UNC paths aren't broken.  Otherwise, any number of
         // / characters are coalesced into one, unless
@@ -1054,7 +1794,6 @@ class Minimatch {
         }
     }
     match(f, partial = this.partial) {
-        this.debug('match', f, this.pattern);
         // short-circuit in the case of busted things.
         // comments, etc.
         if (this.comment) {
@@ -1067,19 +1806,36 @@ class Minimatch {
             return true;
         }
         const options = this.options;
-        // windows: need to use /, not \
-        if (this.isWindows) {
-            f = f.split('\\').join('/');
+        // treat the test path as a set of pathparts. If it was not just
+        // split or checked, check that it can match before splitting it.
+        let split = this.#cachedSplit(f);
+        if (!split) {
+            // the checks look at the path as given, so not if it is
+            // normalized
+            if (!partial &&
+                !this.#form &&
+                (this.#endCheck || this.#literalCheck) &&
+                lastChecked !== f) {
+                lastChecked = f;
+                const can = this.#canMatch(f);
+                if (can === 'no')
+                    return options.flipNegate ? false : this.negate;
+                if (can === 'yes')
+                    return options.flipNegate ? true : !this.negate;
+            }
+            split = this.#split(f);
         }
-        // treat the test path as a set of pathparts.
-        const ff = this.slashSplit(f);
-        this.debug(this.pattern, 'split', ff);
+        const ff = split.parts;
+        // the parts after level 2 resolves them, kept for the next pattern
+        // that tests the same path
+        const resolved = this.#level2 ?
+            (split.resolved ??= this.#levelTwoFileOptimize(ff))
+            : ff;
         // just ONE of the pattern sets in this.set needs to match
         // in order for it to be valid.  If negating, then just one
         // match means that we have failed.
         // Either way, return on the first hit.
         const set = this.set;
-        this.debug(this.pattern, 'set', set);
         // Find the basename of the path by looking for the last non-empty segment
         let filename = ff[ff.length - 1];
         if (!filename) {
@@ -1087,12 +1843,16 @@ class Minimatch {
                 filename = ff[i];
             }
         }
-        for (const pattern of set) {
-            let file = ff;
-            if (options.matchBase && pattern.length === 1) {
-                file = [filename];
-            }
-            const hit = this.matchOne(file, pattern, partial);
+        for (let r = 0; r < set.length; r++) {
+            const pattern = set[r];
+            const shape = partial ? undefined : this.#shapes[r];
+            // level 2 does not change a path of one portion
+            const hit = shape === 'base' ?
+                portionMatch(pattern[0], filename)
+                : shape ? this.#matchShape(resolved, pattern, shape)
+                    : options.matchBase && pattern.length === 1 ?
+                        this.#matchRow([filename], [filename], pattern, partial)
+                        : this.#matchRow(ff, resolved, pattern, partial);
             if (hit) {
                 if (options.flipNegate) {
                     return true;
@@ -1113,14 +1873,11 @@ class Minimatch {
 }
 exports.Minimatch = Minimatch;
 /* c8 ignore start */
-var ast_js_2 = require("./ast.js");
-Object.defineProperty(exports, "AST", { enumerable: true, get: function () { return ast_js_2.AST; } });
 var escape_js_2 = require("./escape.js");
 Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return escape_js_2.escape; } });
 var unescape_js_2 = require("./unescape.js");
 Object.defineProperty(exports, "unescape", { enumerable: true, get: function () { return unescape_js_2.unescape; } });
 /* c8 ignore stop */
-exports.minimatch.AST = ast_js_1.AST;
 exports.minimatch.Minimatch = Minimatch;
 exports.minimatch.escape = escape_js_1.escape;
 exports.minimatch.unescape = unescape_js_1.unescape;
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.js.map
index f0b81f03f38174267674c53a3dcd4633518e300f..6be778acaf8e66730ac57b2c60a961d2f97081f7 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.js.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/index.js.map
@@ -1 +1 @@
-{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAAwC;AACxC,uEAA8D;AAE9D,qCAA8B;AAC9B,2CAAoC;AACpC,+CAAwC;AAqHjC,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,UAA4B,EAAE,EAC9B,EAAE;IACF,IAAA,4CAAkB,EAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QACpD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC,CAAA;AAbY,QAAA,SAAS,aAarB;AAED,wDAAwD;AACxD,MAAM,YAAY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AA;YACnB,CAAC;YACD,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;YACjD,IAAI,GAAG,EAAE,CAAC;gBACR,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;oBACvB,OAAO,IAAI,CAAA;gBACb,CAAC;gBACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAA;YACrB,CAAC;QACH,CAAC;QAED,2DAA2D;QAC3D,8BAA8B;QAC9B,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,iBAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AAhkCD,8BAgkCC;AACD,qBAAqB;AACrB,mCAA8B;AAArB,6FAAA,GAAG,OAAA;AACZ,yCAAoC;AAA3B,mGAAA,MAAM,OAAA;AACf,6CAAwC;AAA/B,uGAAA,QAAQ,OAAA;AACjB,oBAAoB;AACpB,iBAAS,CAAC,GAAG,GAAG,YAAG,CAAA;AACnB,iBAAS,CAAC,SAAS,GAAG,SAAS,CAAA;AAC/B,iBAAS,CAAC,MAAM,GAAG,kBAAM,CAAA;AACzB,iBAAS,CAAC,QAAQ,GAAG,sBAAQ,CAAA","sourcesContent":["import { expand } from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport type { ExtglobType } from './ast.js'\nimport { AST } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\nexport type Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  /** do not expand `{x,y}` style braces */\n  nobrace?: boolean\n  /** do not treat patterns starting with `#` as a comment */\n  nocomment?: boolean\n  /** do not treat patterns starting with `!` as a negation */\n  nonegate?: boolean\n  /** print LOTS of debugging output */\n  debug?: boolean\n  /** treat `**` the same as `*` */\n  noglobstar?: boolean\n  /** do not expand extglobs like `+(a|b)` */\n  noext?: boolean\n  /** return the pattern if nothing matches */\n  nonull?: boolean\n  /** treat `\\\\` as a path separator, not an escape character */\n  windowsPathsNoEscape?: boolean\n  /**\n   * inverse of {@link MinimatchOptions.windowsPathsNoEscape}\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n  /**\n   * Compare a partial path to a pattern. As long as the parts\n   * of the path that are present are not contradicted by the\n   * pattern, it will be treated as a match. This is useful in\n   * applications where you're walking through a folder structure,\n   * and don't yet have the full path, but want to ensure that you\n   * do not walk down paths that can never be a match.\n   */\n  partial?: boolean\n  /** allow matches that start with `.` even if the pattern does not */\n  dot?: boolean\n  /** ignore case */\n  nocase?: boolean\n  /** ignore case only in wildcard patterns */\n  nocaseMagicOnly?: boolean\n  /** consider braces to be \"magic\" for the purpose of `hasMagic` */\n  magicalBraces?: boolean\n  /**\n   * If set, then patterns without slashes will be matched\n   * against the basename of the path if it contains slashes.\n   * For example, `a?b` would match the path `/xyz/123/acb`, but\n   * not `/xyz/acb/123`.\n   */\n  matchBase?: boolean\n  /** invert the results of negated matches */\n  flipNegate?: boolean\n  /** do not collapse multiple `/` into a single `/` */\n  preserveMultipleSlashes?: boolean\n  /**\n   * A number indicating the level of optimization that should be done\n   * to the pattern prior to parsing and using it for matches.\n   */\n  optimizationLevel?: number\n  /** operating system platform */\n  platform?: Platform\n  /**\n   * When a pattern starts with a UNC path or drive letter, and in\n   * `nocase:true` mode, do not convert the root portions of the\n   * pattern into a case-insensitive regular expression, and instead\n   * leave them as strings.\n   *\n   * This is the default when the platform is `win32` and\n   * `nocase:true` is set.\n   */\n  windowsNoMagicRoot?: boolean\n  /**\n   * max number of `{...}` patterns to expand. Default 100_000.\n   */\n  braceExpandMax?: number\n  /**\n   * Max number of non-adjacent `**` patterns to recursively walk down.\n   *\n   * The default of 200 is almost certainly high enough for most purposes,\n   * and can handle absurdly excessive patterns.\n   */\n  maxGlobstarRecursion?: number\n\n  /**\n   * Max depth to traverse for nested extglobs like `*(a|b|c)`\n   *\n   * Default is 2, which is quite low, but any higher value\n   * swiftly results in punishing performance impacts. Note\n   * that this is *not*  relevant when the globstar types can\n   * be safely coalesced into a single set.\n   *\n   * For example, `*(a|@(b|c)|d)` would be flattened into\n   * `*(a|b|c|d)`. Thus, many common extglobs will retain good\n   * performance and  never hit this limit, even if they are\n   * excessively deep and complicated.\n   *\n   * If the limit is hit, then the extglob characters are simply\n   * not parsed, and the pattern effectively switches into\n   * `noextglob: true` mode for the contents of that nested\n   * sub-pattern. This will typically _not_ result in a match,\n   * but is considered a valid trade-off for security and\n   * performance.\n   */\n  maxExtglobRecursion?: number\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?*[(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n  !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) =>\n  !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n  f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) =>\n  f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) =>\n  f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?*[(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process ?\n    (typeof process.env === 'object' &&\n      process.env &&\n      process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n    process.platform\n  : 'posix') as Platform\n\nexport type Sep = '\\\\' | '/'\n\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep =\n  defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed.  Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n  (pattern: string, options: MinimatchOptions = {}) =>\n  (p: string) =>\n    minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    AST: class AST extends orig.AST {\n      /* c8 ignore start */\n      constructor(\n        type: ExtglobType | null,\n        parent?: AST,\n        options: MinimatchOptions = {},\n      ) {\n        super(type, parent, ext(def, options))\n      }\n      /* c8 ignore stop */\n\n      static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n        return orig.AST.fromGlob(pattern, ext(def, options))\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) =>\n      orig.defaults(ext(def, options)),\n\n    makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.makeRe(pattern, ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (\n      list: string[],\n      pattern: string,\n      options: MinimatchOptions = {},\n    ) => orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  return expand(pattern, { max: options.braceExpandMax })\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion.  Otherwise, any series\n// of * is equivalent to a single *.  Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n  new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n  list: string[],\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n  _src?: string\n  _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n  maxGlobstarRecursion: number\n\n  regexp: false | null | MMRegExp\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    // avoid the annoying deprecation flag lol\n    const awe = ('allowWindow' + 'sEscape') as keyof MinimatchOptions\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options[awe] === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.regexp = null\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined ?\n        options.windowsNoMagicRoot\n      : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n\n    // make the set of regexps etc.\n    this.make()\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  debug(..._: unknown[]) {}\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.braceExpand())]\n\n    if (options.debug) {\n      //oxlint-disable-next-line no-console\n      this.debug = (...args: unknown[]) => console.error(...args)\n    }\n\n    this.debug(this.pattern, this.globSet)\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be regexps, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n    this.debug(this.pattern, this.globParts)\n\n    // glob --> regexps\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path.\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          !globMagic.test(s[3])\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [\n            ...s.slice(0, 4),\n            ...s.slice(4).map(ss => this.parse(ss)),\n          ]\n        } else if (isDrive) {\n          return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    this.debug(this.pattern, set)\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1,\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          typeof p[3] === 'string' &&\n          /^[a-z]:$/i.test(p[3])\n        ) {\n          p[2] = '?'\n        }\n      }\n    }\n\n    this.debug(this.pattern, this.set)\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn ** into *\n    if (this.options.noglobstar) {\n      for (const partset of globParts) {\n        for (let j = 0; j < partset.length; j++) {\n          if (partset[j] === '**') {\n            partset[j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  levelTwoFileOptimize(parts: string | string[]) {\n    if (!Array.isArray(parts)) {\n      parts = this.slashSplit(parts)\n    }\n    let didSomething: boolean = false\n\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (\n          p &&\n          p !== '.' &&\n          p !== '..' &&\n          p !== '**' &&\n          !(this.isWindows && /^[a-z]:$/i.test(p))\n        ) {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes,\n        )\n        if (matched) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false,\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean = false,\n  ) {\n    let fileStartIndex = 0\n    let patternStartIndex = 0\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi =\n        fileUNC ? 3\n        : fileDrive ? 0\n        : undefined\n      const pdi =\n        patternUNC ? 3\n        : patternDrive ? 0\n        : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        // start matching at the drive letter index of each\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          patternStartIndex = pdi\n          fileStartIndex = fdi\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // don't need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    if (pattern.includes(GLOBSTAR)) {\n      return this.#matchGlobstar(\n        file,\n        pattern,\n        partial,\n        fileStartIndex,\n        patternStartIndex,\n      )\n    }\n\n    return this.#matchOne(\n      file,\n      pattern,\n      partial,\n      fileStartIndex,\n      patternStartIndex,\n    )\n  }\n\n  #matchGlobstar(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n  ) {\n    // split the pattern into head, tail, and middle of ** delimited parts\n    const firstgs = pattern.indexOf(GLOBSTAR, patternIndex)\n    const lastgs = pattern.lastIndexOf(GLOBSTAR)\n\n    // split the pattern up into globstar-delimited sections\n    // the tail has to be at the end, and the others just have\n    // to be found in order from the head.\n    const [head, body, tail] =\n      partial ?\n        [\n          pattern.slice(patternIndex, firstgs),\n          pattern.slice(firstgs + 1),\n          [],\n        ]\n      : [\n          pattern.slice(patternIndex, firstgs),\n          pattern.slice(firstgs + 1, lastgs),\n          pattern.slice(lastgs + 1),\n        ]\n\n    // check the head, from the current file/pattern index.\n    if (head.length) {\n      const fileHead = file.slice(fileIndex, fileIndex + head.length)\n      if (!this.#matchOne(fileHead, head, partial, 0, 0)) {\n        return false\n      }\n      fileIndex += head.length\n      patternIndex += head.length\n    }\n    // now we know the head matches!\n\n    // if the last portion is not empty, it MUST match the end\n    // check the tail\n    let fileTailMatch: number = 0\n    if (tail.length) {\n      // if head + tail > file, then we cannot possibly match\n      if (tail.length + fileIndex > file.length) return false\n\n      // try to match the tail\n      let tailStart = file.length - tail.length\n      if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n        fileTailMatch = tail.length\n      } else {\n        // affordance for stuff like a/**/* matching a/b/\n        // if the last file portion is '', and there's more to the pattern\n        // then try without the '' bit.\n        if (\n          file[file.length - 1] !== '' ||\n          fileIndex + tail.length === file.length\n        ) {\n          return false\n        }\n        tailStart--\n        if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n          return false\n        }\n        fileTailMatch = tail.length + 1\n      }\n    }\n\n    // now we know the tail matches!\n\n    // the middle is zero or more portions wrapped in **, possibly\n    // containing more ** sections.\n    // so a/**/b/**/c/**/d has become **/b/**/c/**\n    // if it's empty, it means a/**/b, just verify we have no bad dots\n    // if there's no tail, so it ends on /**, then we must have *something*\n    // after the head, or it's not a matc\n    if (!body.length) {\n      let sawSome = !!fileTailMatch\n      for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n        const f = String(file[i])\n        sawSome = true\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      // in partial mode, we just need to get past all file parts\n      return partial || sawSome\n    }\n\n    // now we know that there's one or more body sections, which can\n    // be matched anywhere from the 0 index (because the head was pruned)\n    // through to the length-fileTailMatch index.\n    // split the body up into sections, and note the minimum index it can\n    // be found at (start with the length of all previous segments)\n    // [section, before, after]\n    const bodySegments: [ParseReturn[], number][] = [[[], 0]]\n    let currentBody: [ParseReturn[], number] = bodySegments[0]\n    let nonGsParts = 0\n    const nonGsPartsSums: number[] = [0]\n    for (const b of body) {\n      if (b === GLOBSTAR) {\n        nonGsPartsSums.push(nonGsParts)\n        currentBody = [[], 0]\n        bodySegments.push(currentBody)\n      } else {\n        currentBody[0].push(b)\n        nonGsParts++\n      }\n    }\n    let i = bodySegments.length - 1\n    const fileLength = file.length - fileTailMatch\n    for (const b of bodySegments) {\n      b[1] = fileLength - ((nonGsPartsSums[i--] as number) + b[0].length)\n    }\n\n    return !!this.#matchGlobStarBodySections(\n      file,\n      bodySegments,\n      fileIndex,\n      0,\n      partial,\n      0,\n      !!fileTailMatch,\n    )\n  }\n\n  // return false for \"nope, not matching\"\n  // return null for \"not matching, cannot keep trying\"\n  #matchGlobStarBodySections(\n    file: string[],\n    // pattern section, last possible position for it\n    bodySegments: [ParseReturn[], number][],\n    fileIndex: number,\n    bodyIndex: number,\n    partial: boolean,\n    globStarDepth: number,\n    sawTail: boolean,\n  ): boolean | null {\n    // take the first body segment, and walk from fileIndex to its \"after\"\n    // value at the end\n    // If it doesn't match at that position, we increment, until we hit\n    // that final possible position, and give up.\n    // If it does match, then advance and try to rest.\n    // If any of them fail we keep walking forward.\n    // this is still a bit recursively painful, but it's more constrained\n    // than previous implementations, because we never test something that\n    // can't possibly be a valid matching condition.\n    const bs = bodySegments[bodyIndex]\n    if (!bs) {\n      // just make sure that there's no bad dots\n      for (let i = fileIndex; i < file.length; i++) {\n        sawTail = true\n        const f = file[i]\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      return sawTail\n    }\n\n    // have a non-globstar body section to test\n    const [body, after] = bs\n    while (fileIndex <= after) {\n      const m = this.#matchOne(\n        file.slice(0, fileIndex + body.length),\n        body,\n        partial,\n        fileIndex,\n        0,\n      )\n      // if limit exceeded, no match. intentional false negative,\n      // acceptable break in correctness for security.\n      if (m && globStarDepth < this.maxGlobstarRecursion) {\n        // match! see if the rest match. if so, we're done!\n        const sub = this.#matchGlobStarBodySections(\n          file,\n          bodySegments,\n          fileIndex + body.length,\n          bodyIndex + 1,\n          partial,\n          globStarDepth + 1,\n          sawTail,\n        )\n        if (sub !== false) {\n          return sub\n        }\n      }\n      const f = file[fileIndex]\n      if (\n        f === '.' ||\n        f === '..' ||\n        (!this.options.dot && f.startsWith('.'))\n      ) {\n        return false\n      }\n\n      fileIndex++\n    }\n    // walked off. no point continuing\n    return partial || null\n  }\n\n  #matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n  ) {\n    let fi: number\n    let pi: number\n    let pl: number\n    let fl: number\n    for (\n      fi = fileIndex,\n        pi = patternIndex,\n        fl = file.length,\n        pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      let p = pattern[pi]\n      let f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      // should be impossible.\n      // some invalid regexp stuff in the set.\n      /* c8 ignore start */\n      if (p === false || p === GLOBSTAR) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into regexps.\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though \"\" matches against the\n    // [^/]*? pattern, except in partial mode, where it might\n    // simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase ?\n          options.dot ?\n            starDotExtTestNocaseDot\n          : starDotExtTestNocase\n        : options.dot ? starDotExtTestDot\n        : starDotExtTest)(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase ?\n          options.dot ?\n            qmarksTestNocaseDot\n          : qmarksTestNocase\n        : options.dot ? qmarksTestDot\n        : qmarksTest)(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar =\n      options.noglobstar ? star\n      : options.dot ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return (\n            typeof p === 'string' ? regExpEscape(p)\n            : p === GLOBSTAR ? GLOBSTAR\n            : p._src\n          )\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        const filtered = pp.filter(p => p !== GLOBSTAR)\n\n        // For partial matches, we need to make the pattern match\n        // any prefix of the full path. We do this by generating\n        // alternative patterns that match progressively longer prefixes.\n        if (this.partial && filtered.length >= 1) {\n          const prefixes: string[] = []\n          for (let i = 1; i <= filtered.length; i++) {\n            prefixes.push(filtered.slice(0, i).join('/'))\n          }\n          return '(?:' + prefixes.join('|') + ')'\n        }\n\n        return filtered.join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // In partial mode, '/' should always match as it's a valid prefix for any pattern\n    if (this.partial) {\n      re = '^(?:\\\\/|' + open + re.slice(1, -1) + close + ')$'\n    }\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (const pattern of set) {\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n"]}
\ No newline at end of file
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAAwC;AACxC,6EAAoE;AACpE,uEAA8D;AAC9D,2CAAoC;AACpC,+CAAwC;AAExC,MAAM,wBAAwB,GAAG,OAAO,CAAA;AACxC,MAAM,+BAA+B,GAAG,GAAG,CAAA;AAC3C,0CAA0C;AAC1C,MAAM,OAAO,GAAG,CAAC,aAAa,GAAG,SAAS,CAA2B,CAAA;AAyG9D,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,OAA0B,EAC1B,EAAE;IACF,IAAA,4CAAkB,EAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,EAAE,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QACrD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,OAAO,eAAe,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;AACnD,CAAC,CAAA;AAbY,QAAA,SAAS,aAarB;AAED,wEAAwE;AACxE,uEAAuE;AACvE,qEAAqE;AACrE,kCAAkC;AAClC,oEAAoE;AACpE,qEAAqE;AACrE,mEAAmE;AACnE,mDAAmD;AACnD,IAAI,KAAK,GAAG,IAAI,GAAG,EAA2C,CAAA;AAC9D,IAAI,QAAQ,GAAG,IAAI,GAAG,EAA2C,CAAA;AACjE,IAAI,SAAS,GAAG,CAAC,CAAA;AACjB,IAAI,gBAAgB,GAAG,CAAC,CAAA;AACxB,MAAM,QAAQ,GAAG,GAAG,CAAA;AACpB,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE,CAAA;AAC9B,MAAM,mBAAm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CAAC;gBACR,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;oBACvB,OAAO,IAAI,CAAA;gBACb,CAAC;gBACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAA;YACrB,CAAC;QACH,CAAC;QAED,2DAA2D;QAC3D,8BAA8B;QAC9B,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,iBAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AA/+CD,8BA++CC;AACD,qBAAqB;AACrB,yCAAoC;AAA3B,mGAAA,MAAM,OAAA;AACf,6CAAwC;AAA/B,uGAAA,QAAQ,OAAA;AAEjB,oBAAoB;AACpB,iBAAS,CAAC,SAAS,GAAG,SAAS,CAAA;AAC/B,iBAAS,CAAC,MAAM,GAAG,kBAAM,CAAA;AACzB,iBAAS,CAAC,QAAQ,GAAG,sBAAQ,CAAA","sourcesContent":["import { expand } from 'brace-expansion'\nimport { Matcher, type Form } from '@isaacs/nonrecursive-glob-match'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\nconst DEFAULT_BRACE_EXPAND_MAX = 100_000\nconst DEFAULT_GLOB_STAR_RECURSION_MAX = 200\n// avoid the annoying deprecation flag lol\nconst AWE_KEY = ('allowWindow' + 'sEscape') as keyof MinimatchOptions\n\nexport type Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  /** do not expand `{x,y}` style braces */\n  nobrace?: boolean\n  /** do not treat patterns starting with `#` as a comment */\n  nocomment?: boolean\n  /** do not treat patterns starting with `!` as a negation */\n  nonegate?: boolean\n  /** treat `**` the same as `*` */\n  noglobstar?: boolean\n  /** do not expand extglobs like `+(a|b)` */\n  noext?: boolean\n  /** return the pattern if nothing matches */\n  nonull?: boolean\n  /** treat `\\\\` as a path separator, not an escape character */\n  windowsPathsNoEscape?: boolean\n  /**\n   * inverse of {@link MinimatchOptions.windowsPathsNoEscape}\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n  /**\n   * Compare a partial path to a pattern. As long as the parts\n   * of the path that are present are not contradicted by the\n   * pattern, it will be treated as a match. This is useful in\n   * applications where you're walking through a folder structure,\n   * and don't yet have the full path, but want to ensure that you\n   * do not walk down paths that can never be a match.\n   */\n  partial?: boolean\n  /** allow matches that start with `.` even if the pattern does not */\n  dot?: boolean\n  /** ignore case */\n  nocase?: boolean\n  /** ignore case only in wildcard patterns */\n  nocaseMagicOnly?: boolean\n  /**\n   * Normalize unicode in the pattern and in each portion of the\n   * tested paths, with this form. `true` means `'NFC'`.\n   */\n  normalize?: boolean | Form\n  /** consider braces to be \"magic\" for the purpose of `hasMagic` */\n  magicalBraces?: boolean\n  /**\n   * If set, then patterns without slashes will be matched\n   * against the basename of the path if it contains slashes.\n   * For example, `a?b` would match the path `/xyz/123/acb`, but\n   * not `/xyz/acb/123`.\n   */\n  matchBase?: boolean\n  /** invert the results of negated matches */\n  flipNegate?: boolean\n  /** do not collapse multiple `/` into a single `/` */\n  preserveMultipleSlashes?: boolean\n  /**\n   * A number indicating the level of optimization that should be done\n   * to the pattern prior to parsing and using it for matches.\n   * At level 2 or higher, throws RangeError if splitting `**` and `..`\n   * would make more than `braceExpandMax` patterns, or add more than\n   * 1,000,000 path portions.\n   */\n  optimizationLevel?: number\n  /** operating system platform */\n  platform?: Platform\n  /**\n   * When a pattern starts with a UNC path or drive letter, and in\n   * `nocase:true` mode, do not convert the root portions of the\n   * pattern into a case-insensitive regular expression, and instead\n   * leave them as strings.\n   *\n   * This is the default when the platform is `win32` and\n   * `nocase:true` is set.\n   */\n  windowsNoMagicRoot?: boolean\n  /**\n   * max number of `{...}` patterns to expand. Default 100_000.\n   *\n   * At `optimizationLevel` 2 or higher, this also limits the\n   * patterns made when `**` is followed by `..`. Over this limit,\n   * construction throws a RangeError.\n   */\n  braceExpandMax?: number\n  /**\n   * Max number of non-adjacent `**` patterns to recursively walk down.\n   *\n   * The default of 200 is almost certainly high enough for most purposes,\n   * and can handle absurdly excessive patterns.\n   */\n  maxGlobstarRecursion?: number\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options?: MinimatchOptions,\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options?.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return cachedMinimatch(pattern, options).match(p)\n}\n\n// The Minimatch objects that minimatch() used most recently, by options\n// and then by pattern. When the cache is full, it becomes the old one,\n// and the objects used from the old one are moved back to a new one.\n// So it keeps 256 to 512 objects.\n// The patterns can come from users, so the cache is also bounded by\n// the total weight of the objects (see cacheWeight()), and an object\n// that is too heavy is never kept. Otherwise a few unique patterns\n// with large brace expansions would fill the heap.\nlet cache = new Map>()\nlet oldCache = new Map>()\nlet cacheSize = 0\nlet cacheTotalWeight = 0\nconst cacheMax = 256\nconst cacheMaxWeight = 1 << 15\nconst cacheMaxEntryWeight = 1 << 12\n\n// About the memory that a compiled object keeps: the pattern and the\n// expanded patterns, of which each row in set is made.\nconst cacheWeight = (mm: Minimatch): number => {\n  let w = mm.pattern.length\n  for (const s of mm.globSet) {\n    w += s.length + 1\n    if (w > cacheMaxEntryWeight) break\n  }\n  return w\n}\n\ntype BooleanOption =\n  | 'nobrace'\n  | 'nocomment'\n  | 'nonegate'\n  | 'noglobstar'\n  | 'noext'\n  | 'nonull'\n  | 'windowsPathsNoEscape'\n  | 'allowWindowsEscape'\n  | 'partial'\n  | 'dot'\n  | 'nocase'\n  | 'nocaseMagicOnly'\n  | 'magicalBraces'\n  | 'matchBase'\n  | 'flipNegate'\n  | 'preserveMultipleSlashes'\n  | 'windowsNoMagicRoot'\ntype OtherOption =\n  | 'normalize'\n  | 'platform'\n  | 'optimizationLevel'\n  | 'braceExpandMax'\n  | 'maxGlobstarRecursion'\n// tsc fails here if a new option is in neither type. Add it to\n// optionsKey() too.\nconst allOptionsKeyed: [\n  Exclude,\n] extends [never] ?\n  true\n: never = true\nvoid allOptionsKeyed\n\n// 0, 1 or 2 for undefined, falsy or truthy.\nconst tri = (v: unknown) =>\n  v === undefined ? 0\n  : v ? 2\n  : 1\n\n// The weight of each boolean option's base-3 digit in the key. The\n// weights below 24 are for optimizationLevel (1), platform (3) and\n// windowsPathsNoEscape (12). tsc fails here if a boolean option is\n// not in the list.\nconst booleanWeights = new Map(\n  Object.keys({\n    nobrace: 0,\n    nocomment: 0,\n    nonegate: 0,\n    noglobstar: 0,\n    noext: 0,\n    nonull: 0,\n    partial: 0,\n    dot: 0,\n    nocase: 0,\n    nocaseMagicOnly: 0,\n    magicalBraces: 0,\n    matchBase: 0,\n    flipNegate: 0,\n    preserveMultipleSlashes: 0,\n    windowsNoMagicRoot: 0,\n  } satisfies Record<\n    Exclude,\n    0\n  >).map((k, i) => [k, 24 * 3 ** i]),\n)\n\n// The cache key for a set of options. It is a number, unless an\n// option is set to a value that the number can not show, such as\n// normalize or an uncommon platform. Then it is a JSON string.\n// The defaults give 0, the same key as no options.\n// It only reads the keys that are set, so that the speed does not\n// depend on the shape of the options object.\nconst optionsKey = (o: MinimatchOptions): number | string => {\n  let n = 0\n  let wpe = false\n  // inherited keys too, because Minimatch reads them\n  // oxlint-disable-next-line guard-for-in\n  for (const k in o) {\n    const v = (o as Record)[k]\n    switch (k) {\n      // the same test as the Minimatch constructor\n      case 'windowsPathsNoEscape':\n        if (v) wpe = true\n        break\n      case AWE_KEY:\n        if (v === false) wpe = true\n        break\n\n      case 'platform': {\n        // the same test as the Minimatch constructor\n        const p = v || defaultPlatform\n        if (p === defaultPlatform) break\n        if (p === 'darwin') n += 3\n        else if (p === 'win32') n += 6\n        else if (p === 'linux') n += 9\n        else return JSON.stringify(o)\n        break\n      }\n\n      case 'optimizationLevel':\n        // The same tests as Minimatch: 1 when undefined, then >= 2,\n        // >= 1, or else 0. The default level 1 adds 0.\n        if (v === undefined) break\n        n +=\n          (v as number) >= 2 ? 1\n          : (v as number) >= 1 ? 0\n          : 2\n        break\n\n      case 'braceExpandMax':\n        if (v !== undefined && v !== DEFAULT_BRACE_EXPAND_MAX) {\n          return JSON.stringify(o)\n        }\n        break\n      case 'maxGlobstarRecursion':\n        if (v !== undefined && v !== DEFAULT_GLOB_STAR_RECURSION_MAX) {\n          return JSON.stringify(o)\n        }\n        break\n      case 'normalize':\n        if (v !== undefined) return JSON.stringify(o)\n        break\n\n      default:\n        // unknown keys have no weight\n        n += (booleanWeights.get(k) ?? 0) * tri(v)\n    }\n  }\n  return wpe ? n + 12 : n\n}\n\n// A copy, so a later change to the options can not change it. Unlike\n// a spread, it keeps the inherited keys, which optionsKey() and the\n// Minimatch constructor also read.\nconst copyOptions = (o?: MinimatchOptions) => {\n  const copy: Record = {}\n  // oxlint-disable-next-line guard-for-in\n  for (const k in o) copy[k] = (o as Record)[k]\n  return copy as MinimatchOptions\n}\n\nconst cachedMinimatch = (pattern: string, options?: MinimatchOptions) => {\n  const key = options ? optionsKey(options) : 0\n  let mm = cache.get(key)?.get(pattern)\n  if (mm) return mm\n  mm =\n    oldCache.get(key)?.get(pattern) ??\n    new Minimatch(pattern, copyOptions(options))\n  const weight = cacheWeight(mm)\n  // too big to keep, so it is compiled again each time\n  if (weight > cacheMaxEntryWeight) return mm\n  if (\n    cacheSize >= cacheMax ||\n    cacheTotalWeight + weight > cacheMaxWeight\n  ) {\n    oldCache = cache\n    cache = new Map()\n    cacheSize = 0\n    cacheTotalWeight = 0\n  }\n  let byPattern = cache.get(key)\n  if (!byPattern) cache.set(key, (byPattern = new Map()))\n  byPattern.set(pattern, mm)\n  cacheSize++\n  cacheTotalWeight += weight\n  return mm\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process ?\n    process.env?.__MINIMATCH_TESTING_PLATFORM__ || process.platform\n  : 'posix') as Platform\n\nexport type Sep = '\\\\' | '/'\n\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep =\n  defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\nexport const filter = (pattern: string, options?: MinimatchOptions) => {\n  let mm: Minimatch | undefined\n  return (p: string) => (mm ??= cachedMinimatch(pattern, options)).match(p)\n}\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) =>\n      orig.defaults(ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (\n      list: string[],\n      pattern: string,\n      options: MinimatchOptions = {},\n    ) => orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  // brace-expansion turns each escaped backslash '\\\\' into a single '\\',\n  // which then escapes the next character instead, and can turn an\n  // escaped magic character (for example '\\\\\\*') into a live one.\n  // Double every pair, so an escaped backslash comes back out still\n  // escaped. The parity of each run of backslashes is unchanged.\n  let p = pattern.replace(/\\\\\\\\/g, '\\\\\\\\\\\\\\\\')\n  // brace-expansion does not know about [...] classes. In\n  // windowsPathsNoEscape mode, escape() writes a literal brace as '[{]'\n  // or '[}]'. Escape the brace for brace-expansion, which removes that\n  // backslash again, leaving '[{]' or '[}]'.\n  if (options.windowsPathsNoEscape || options[AWE_KEY] === false) {\n    p = p.replace(/\\[([{}])\\]/g, '[\\\\$1]')\n  }\n  return expand(p, { max: options.braceExpandMax })\n}\nminimatch.braceExpand = braceExpand\n\n// A numeric range with at least this many values is matched as one\n// pattern portion, rather than expanded. For a glob walk, that is\n// one directory read, in place of a stat for each value.\nconst RANGE_MIN = 100\n// a {lo..hi} range that is not escaped, and not a ${...} variable\nconst rangeRe = /(? {\n  const stack: string[] = []\n  for (let i = 0; i < portion.length; i++) {\n    const c = portion.charAt(i)\n    if (c === '\\\\') {\n      i++\n    } else if (c === mark) {\n      if (stack.some(t => t !== '@' && t !== '?')) return true\n    } else if (portion.charAt(i + 1) === '(' && '!?+*@'.includes(c)) {\n      stack.push(c)\n      i++\n    } else if (c === ')') {\n      stack.pop()\n    }\n  }\n  return false\n}\n\nexport const match = (\n  list: string[],\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\n\n// Index of the `]` that closes the class that starts at `start`,\n// or -1 if it is not closed. Posix classes such as `[:alpha:]` are\n// not skipped, so this can find a `]` before the real end. That\n// only makes a class look less like a literal.\nconst classEnd = (pattern: string, start: number) => {\n  let i = start + 1\n  if (pattern.charAt(i) === '!' || pattern.charAt(i) === '^') i++\n  let sawStart = false\n  for (; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === ']' && sawStart) return i\n    sawStart = true\n    if (c === '\\\\') i++\n  }\n  return -1\n}\n\n// If a path portion pattern has no magic, return the string it\n// matches. Otherwise, return undefined. This can report magic for\n// a pattern that is in fact literal (eg, `[]`), but never the\n// reverse, so a string result is always safe to compare directly.\nconst literal = (pattern: string, noext: boolean): string | undefined => {\n  if (!noext && (pattern === '+()' || pattern === '@()')) return pattern\n  let lit = ''\n  for (let i = 0; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      // a trailing \\ is a literal \\\n      lit += pattern.charAt(++i) || c\n    } else if (c === '*' || c === '?') {\n      return undefined\n    } else if (c === '[') {\n      const close = classEnd(pattern, i)\n      if (close === -1) {\n        // not closed, so the [ is a literal\n        lit += c\n        continue\n      }\n      // a class of one char, such as `[*]` or `[\\b]`, is a literal\n      let body = pattern.slice(i + 1, close)\n      if (body.startsWith('\\\\')) body = body.slice(1)\n      if ([...body].length !== 1 || '!^'.includes(pattern.charAt(i + 1))) {\n        return undefined\n      }\n      lit += body\n      i = close\n    } else if (\n      !noext &&\n      '+@!'.includes(c) &&\n      pattern.charAt(i + 1) === '(' &&\n      pattern.includes(')', i + 2)\n    ) {\n      return undefined\n    } else {\n      lit += c\n    }\n  }\n  return lit\n}\n\n// The matching engine compiles and walks extglobs recursively, so a\n// path portion with very many extglobs (nested, such as `*(*(*(a)))`,\n// or in a row, such as `?(a)?(a)?(a)`) can exhaust the call stack.\n// Portions with more than this many extglobs are rejected.\nconst MAX_EXTGLOBS = 256\n\n// The number of extglob openers, such as `*(`, in a path portion\n// pattern. Chars in a class are counted too, so this can be more than\n// the number of extglobs, but never less.\nconst extglobCount = (pattern: string): number => {\n  let n = 0\n  for (let i = 0; i < pattern.length - 1; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      i++\n    } else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') {\n      n++\n      i++\n    }\n  }\n  return n\n}\n\nconst assertValidExtglobs = (pattern: string) => {\n  if (extglobCount(pattern) > MAX_EXTGLOBS) {\n    throw new TypeError('pattern has too many extglobs')\n  }\n}\n\n// True if the portion pattern has the same meaning as an alternative\n// inside `@(...)`. It must not have a `|` or `)` that is not in a\n// closed extglob (those are literal at the top level), an extglob\n// that is not closed (the `)` of the `@(...)` would close it), or a\n// trailing `\\` (it would escape the next `|`). A pattern that is\n// only an empty extglob, such as `?()`, is literal on its own, but\n// not in `@(...)`. Posix classes such as `[:alpha:]` can hide a `]`\n// from classEnd, so patterns with them are not merged.\nconst extSafe = (pattern: string) => {\n  if (/^[?*+@]\\(\\)$/.test(pattern) || pattern.includes('[:')) return false\n  let depth = 0\n  for (let i = 0; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      if (++i === pattern.length) return false\n    } else if (c === '[') {\n      const close = classEnd(pattern, i)\n      if (close !== -1) i = close\n    } else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') {\n      depth++\n      i++\n    } else if (c === ')') {\n      if (!depth--) return false\n    } else if (c === '|' && !depth) {\n      return false\n    }\n  }\n  return !depth\n}\n\n// The last path that Minimatch#match split, and its parts. A path is\n// often tested against many patterns in a row (such as a list of\n// ignore patterns), so this saves splitting it again. The parts are\n// never changed, so they can be shared.\nlet lastSplit: SplitPath | undefined\n\n/**\n * A path that Minimatch#match split, with the settings that the split\n * depends on. `resolved` is the parts after optimizationLevel 2 has\n * resolved `.` and `..` in them, which only depends on the same\n * settings, once a level 2 Minimatch has needed them.\n */\nexport type SplitPath = {\n  f: string\n  isWindows: boolean\n  preserveMultipleSlashes: boolean\n  normalize: Form | undefined\n  parts: string[]\n  resolved?: string[]\n}\n\n// The last path that Minimatch#match checked before splitting it. If\n// the same path is checked again, it is being tested against many\n// patterns, so it is split and the parts are kept for the others.\nlet lastChecked: string | undefined\n\nexport type ParseReturnFiltered = string | Matcher | typeof GLOBSTAR\n\n/**\n * The rows that Minimatch#match can match without splitting the path:\n * `**` and one more portion (`tail`), a portion with `**` on each side\n * of it (`mid`), a portion and then `**` (`head`), or one portion that\n * matches the basename of the path, with matchBase (`base`).\n */\nexport type RowShape = 'tail' | 'mid' | 'head' | 'base'\n\n// true if a pattern portion that is not ** matches a path portion.\n// An empty path portion only matches an empty pattern portion. A path\n// portion never has a `/`, so the Matcher does not need to check it.\nconst portionMatch = (p: string | Matcher, f: string) =>\n  typeof p === 'string' ? f === p : f !== '' && p.testUnchecked(f)\n\n// Where the last portion of a row matches in a path: the start of the\n// last portion of the path, or of the one before a trailing `/`. -1 if\n// it matches neither.\nconst endIndex = (\n  p: string | Matcher,\n  last: string,\n  lastStart: number,\n  prev: string | undefined,\n  prevStart: number,\n) =>\n  portionMatch(p, last) ? lastStart\n  : prev !== undefined && portionMatch(p, prev) ? prevStart\n  : -1\n\nconst isDots = (p: string) => p === '.' || p === '..'\n\n// a Windows drive letter portion, like `c:`\nconst isDrive = (p: ParseReturn | undefined) =>\n  typeof p === 'string' && /^[a-z]:$/i.test(p)\n\n// true for the `UNC` portion of a long UNC root, //?/UNC/host/share\nconst isLongUNC = (p: ParseReturn | undefined) =>\n  typeof p === 'string' && /^unc$/i.test(p)\n\n// The index of the host in a row or split path that starts with a\n// Windows UNC root: 2 for `//host/share`, and 4 for\n// `//?/UNC/host/share`. Otherwise -1. `//?/c:` is not one.\nconst uncHost = (p: ParseReturn[]) => {\n  if (p[0] !== '' || p[1] !== '') return -1\n  const h =\n    p[2] !== '?' ? 2\n    : isLongUNC(p[3]) ? 4\n    : -1\n  const host = p[h]\n  const share = p[h + 1]\n  return (\n      h !== -1 &&\n        host !== undefined &&\n        host !== '' &&\n        host !== GLOBSTAR &&\n        share !== undefined &&\n        share !== '' &&\n        share !== GLOBSTAR\n    ) ?\n      h\n    : -1\n}\n\n// true if ** can walk the path portion: not `.` or `..`, and not a\n// dotfile unless `dot` is set\nconst walkable = (p: string, dot: boolean) =>\n  !isDots(p) && (dot || !p.startsWith('.'))\n\n// True if a portion of the path from `start` to `end` can not be\n// walked by **: one that starts with `.`, or with `dot`, one that is\n// `.` or `..`. `start` is the start of a portion, and `end` is the end\n// of the path, or just after a separator.\nconst dotPortion = (\n  f: string,\n  start: number,\n  end: number,\n  dot: boolean,\n  sep: PathSeps,\n) => {\n  for (let k = start; k < end;) {\n    if (f.charCodeAt(k) === 46) {\n      if (!dot) return true\n      const n = f.charCodeAt(k + 1) === 46 ? k + 2 : k + 1\n      if (n >= end || isSep(f.charCodeAt(n), sep)) return true\n    }\n    // the start of the next portion, after any run of separators\n    const s = nextSep(f, k, sep)\n    if (s === -1) return false\n    k = s + 1\n    while (k < end && isSep(f.charCodeAt(k), sep)) k++\n  }\n  return false\n}\n\n/**\n * The separators that a path has: only `/`, only `\\` (a Windows path\n * with no `/`), or both. Scanning for the ones it has is faster.\n */\nexport type PathSeps = '/' | '\\\\' | 'both'\n\nconst isSep = (c: number, sep: PathSeps) =>\n  sep === '/' ? c === 47\n  : sep === '\\\\' ? c === 92\n  : c === 47 || c === 92\n\n// the index of the first separator at or after `from`, or -1\nconst nextSep = (f: string, from: number, sep: PathSeps) => {\n  if (sep !== 'both') return f.indexOf(sep, from)\n  const s = f.indexOf('/', from)\n  const b = f.indexOf('\\\\', from)\n  return (\n    s === -1 ? b\n    : b === -1 ? s\n    : Math.min(s, b)\n  )\n}\n\n// the index of the last separator at or before `from`, or -1\nconst lastSep = (f: string, from: number, sep: PathSeps) =>\n  sep !== 'both' ?\n    f.lastIndexOf(sep, from)\n  : Math.max(f.lastIndexOf('/', from), f.lastIndexOf('\\\\', from))\n\n/**\n * A pattern row split on its first and last `**`, from a start\n * index. Each body segment has the number of path portions that it\n * and the ones after it need, to find the last index where it can\n * start in a path.\n */\nexport type GlobstarParts = {\n  head: ParseReturn[]\n  body: ParseReturn[]\n  tail: ParseReturn[]\n  segments: [segment: ParseReturn[], need: number][]\n}\nexport type ParseReturn = ParseReturnFiltered | false\n\n// What parse() returns in place of a Matcher while make() builds and\n// merges the rows. Most of the Matchers in rows that are merged would\n// never be used, so they are only made for the rows that are left.\nconst PENDING = {} as Matcher\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n  maxGlobstarRecursion: number\n  // the path can be checked against the last portion, and the string\n  // portions, of each row before it is split. See #canMatch.\n  #endCheck: boolean\n  #literalCheck: boolean\n  // level 2 resolves `.` and `..` portions in the path\n  #level2: boolean\n  // the unicode normalization form, if any\n  #form: Form | undefined\n  // the string portions of each row in the set\n  #literals: string[][] = []\n  // the rows that #canMatch can match without splitting the path\n  #shapes: (RowShape | undefined)[] = []\n  // the rows whose last portion can be checked against the path's\n  #endRows: boolean[] = []\n  // brace expansion can make the same portion in many rows, so they\n  // share one Matcher, and the states that it caches\n  #matchers = new Map()\n  // parse() returns PENDING in place of a Matcher\n  #pending = false\n  // the char that marks numeric ranges in globSet, if any\n  #rangeMark?: string\n  // the GlobstarParts of each pattern row, by start index and partial\n  #globstarParts = new WeakMap()\n\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.maxGlobstarRecursion =\n      options.maxGlobstarRecursion ?? DEFAULT_GLOB_STAR_RECURSION_MAX\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options[AWE_KEY] === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined ?\n        options.windowsNoMagicRoot\n      : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n    this.#endCheck = !this.preserveMultipleSlashes\n    this.#level2 = (options.optimizationLevel ?? 1) >= 2\n    const n = options.normalize\n    this.#form = n === true ? 'NFC' : n || undefined\n\n    // make the set of Matchers etc.\n    this.make()\n\n    // On Windows, the portions of a row up to its drive letter or UNC\n    // share are skipped or compared without case, if the path has one\n    // too. So the checks only use the portions after it.\n    const drives = this.set.map(row => this.#rootIndex(row))\n    this.#endRows = this.set.map(\n      (row, r) => this.#endCheck && row.length - 1 > drives[r]!,\n    )\n    // with the end check, the last portion is already checked\n    this.#literals = this.set.map((row, r) => {\n      const end = this.#endRows[r] ? row.length - 1 : row.length\n      const lits = row\n        .slice(drives[r]! + 1, end)\n        .filter((p): p is string => typeof p === 'string' && !!p)\n      return [...new Set(lits)]\n    })\n    this.#literalCheck = this.#literals.some(l => l.length)\n    this.#shapes = this.set.map((row, r) => {\n      const [p0, p1, p2] = row\n      if (this.#endRows[r] && row.length === 2) {\n        if (p0 === GLOBSTAR && p1 !== GLOBSTAR) return 'tail'\n      }\n      // the basename of a path that is split on / is its last portion,\n      // or the one before a trailing /, the same as the end check\n      if (\n        this.#endRows[r] &&\n        options.matchBase &&\n        row.length === 1 &&\n        p0 !== GLOBSTAR &&\n        p0 !== ''\n      ) {\n        return 'base'\n      }\n      // the portion must not be a root, or '', which can be a\n      // different portion on Windows (where //x paths get an extra '')\n      if (!this.#endCheck || drives[r] !== -1) return undefined\n      if (\n        row.length === 3 &&\n        p0 === GLOBSTAR &&\n        p2 === GLOBSTAR &&\n        p1 !== GLOBSTAR &&\n        p1 !== '' &&\n        // the portion between is only matched below this limit\n        this.maxGlobstarRecursion > 0\n      ) {\n        return 'mid'\n      }\n      if (\n        row.length === 2 &&\n        p1 === GLOBSTAR &&\n        p0 !== GLOBSTAR &&\n        p0 !== ''\n      ) {\n        return 'head'\n      }\n      return undefined\n    })\n  }\n\n  // a string portion of a pattern, normalized if the option is set\n  #norm(p: string) {\n    return this.#form ? p.normalize(this.#form) : p\n  }\n\n  // On Windows, the index of the last root portion of a row, as\n  // #matchRow finds it: 0 for `c:/...`, 3 for `//?/c:/...` and\n  // `//host/share/...`, and 5 for `//?/UNC/host/share/...`. Otherwise\n  // -1.\n  #rootIndex(row: ParseReturn[]) {\n    if (!this.isWindows) return -1\n    if (isDrive(row[0])) return 0\n    const uncDrive =\n      row[0] === '' && row[1] === '' && row[2] === '?' && isDrive(row[3])\n    if (uncDrive) return 3\n    const h = uncHost(row)\n    return h === -1 ? -1 : h + 1\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.#expandBraces())]\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be Matchers, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.#slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n\n    // glob --> Matchers\n    this.#pending = true\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path. The root of a long UNC\n        // path, //?/UNC/host/share, is 6 portions.\n        const n = s[2] === '?' && isLongUNC(s[3]) ? 6 : 4\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          s.slice(3, n).every(p => !globMagic.test(p))\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [\n            ...s.slice(0, n).map(p => this.#norm(p)),\n            ...s.slice(n).map(ss => this.parse(ss)),\n          ]\n        } else if (isDrive) {\n          return [\n            this.#norm(s[0]!),\n            ...s.slice(1).map(ss => this.parse(ss)),\n          ]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1,\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          (isDrive(p[3]) || isLongUNC(this.globParts[i][3]))\n        ) {\n          if (isLongUNC(this.globParts[i][3])) p[3] = 'UNC'\n          p[2] = '?'\n        }\n      }\n    }\n\n    // with noext, `@(...)` would be literal\n    if (!options.noext) this.mergeRows()\n\n    this.#pending = false\n    this.set.forEach((row, i) => {\n      for (let k = 0; k < row.length; k++) {\n        if (row[k] === PENDING) {\n          row[k] = this.parse(this.globParts[i]![k]!) as Matcher\n        }\n      }\n    })\n  }\n\n  // Merge rows that only differ in one portion, where each of them\n  // is a Matcher, into one row that matches any of them with\n  // `@(a|b|...)`. Then a path is only walked once for all of them,\n  // for example with `**/*.{js,ts}`.\n  mergeRows() {\n    let merged = true\n    while (merged) {\n      merged = false\n      // a single row cannot be merged with anything\n      if (this.set.length < 2) return\n      let keys = this.#mergeKeys()\n      const len = Math.max(0, ...this.set.map(r => r.length))\n      for (let k = 0; k < len; k++) {\n        // the rows that are the same other than at portion k, keyed\n        // by the ids of the parts before k and the parts after k,\n        // which are at most the number of rows\n        const groups = new Map()\n        const R = this.set.length + 1\n        this.set.forEach((row, i) => {\n          if (\n            !(row[k] instanceof Matcher || row[k] === PENDING) ||\n            !extSafe(this.globParts[i]![k]!)\n          ) {\n            return\n          }\n          const { pre, suf } = keys[i]!\n          const key = pre[k]! * R + suf[k + 1]!\n          const g = groups.get(key)\n          if (g) g.push(i)\n          else groups.set(key, [i])\n        })\n        const drop = new Set()\n        for (const g of groups.values()) {\n          if (g.length < 2) continue\n          const [first, ...rest] = g as [number, ...number[]]\n          const alts = g.map(i => this.globParts[i]![k]!)\n          const glob = `@(${alts.join('|')})`\n          // merging is only an optimization, so leave the rows as they\n          // are if the merged portion would have too many extglobs\n          if (extglobCount(glob) > MAX_EXTGLOBS) continue\n          this.globParts[first]![k] = glob\n          this.set[first]![k] = this.parse(glob) as Matcher\n          for (const i of rest) drop.add(i)\n        }\n        if (drop.size) {\n          merged = true\n          this.set = this.set.filter((_, i) => !drop.has(i))\n          this.globParts = this.globParts.filter((_, i) => !drop.has(i))\n          // every merge drops a row, so this happens at most once per row\n          if (this.set.length < 2) return\n          keys = this.#mergeKeys()\n        }\n      }\n    }\n  }\n\n  // For each row, number ids for its prefixes and suffixes, such that\n  // pre[k] identifies parts[0..k) and suf[k] identifies parts[k..n).\n  // Two rows are the same other than at portion k exactly when they\n  // have the same pre[k] and suf[k + 1]. This is linear in the size of\n  // the rows, where joining the whole row for every k was quadratic.\n  #mergeKeys(): { pre: number[]; suf: number[] }[] {\n    const partIds = new Map()\n    const ids = this.globParts.map(parts =>\n      parts.map(s => {\n        let id = partIds.get(s)\n        if (id === undefined) partIds.set(s, (id = partIds.size))\n        return id\n      }),\n    )\n    // ids are only compared at the same k, so they are numbered per\n    // portion, with 0 for the empty prefix or suffix. Then they are\n    // at most the number of rows, and id * P + part id is a safe\n    // integer key for any set that fits in memory.\n    const P = partIds.size\n    const len = Math.max(0, ...ids.map(r => r.length))\n    const keys = ids.map(r => ({\n      pre: [0] as number[],\n      suf: new Array(r.length + 1).fill(0),\n    }))\n    for (let k = 0; k < len; k++) {\n      const m = new Map()\n      ids.forEach((r, i) => {\n        if (k >= r.length) return\n        const { pre } = keys[i]!\n        const key = pre[k]! * P + r[k]!\n        let id = m.get(key)\n        if (id === undefined) m.set(key, (id = m.size + 1))\n        pre.push(id)\n      })\n    }\n    for (let k = len - 1; k >= 0; k--) {\n      const m = new Map()\n      ids.forEach((r, i) => {\n        if (k >= r.length) return\n        const { suf } = keys[i]!\n        const key = suf[k + 1]! * P + r[k]!\n        let id = m.get(key)\n        if (id === undefined) m.set(key, (id = m.size + 1))\n        suf[k] = id\n      })\n    }\n    return keys\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn ** into *\n    if (this.options.noglobstar) {\n      for (const partset of globParts) {\n        for (let j = 0; j < partset.length; j++) {\n          if (partset[j] === '**') {\n            partset[j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      // .. can not remove the root of a Windows path\n      const root = this.#rootIndex(parts) + 1\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (\n            set.length > root &&\n            prev &&\n            prev !== '..' &&\n            prev !== '.' &&\n            prev !== '**'\n          ) {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  // Check the path against each row before it is split. 'no' if no\n  // row can match, so it does not need to be split. 'yes' if a row of\n  // `**` and one more portion matches. 'maybe' if it must be split to\n  // know. None of this applies with partial, where the path can end\n  // before the row does.\n  //\n  // On Windows, `\\` is a separator in the path too, and the portions of\n  // a row up to its drive letter or UNC share are not checked (see\n  // #rootIndex).\n  //\n  // Each string portion of a row must be a portion of the path, so the\n  // path must contain it. Level 2 can only take portions out of the\n  // path, so this is still true then.\n  //\n  // The last portion of a row must match the last portion of the path,\n  // or the one before a trailing `/` (as a/* and a/**/* match a/b/).\n  // This does not apply to rows that end in **, rows that end in a\n  // root, or preserveMultipleSlashes (which can leave more\n  // than one '' at the end). At level 2, it does not apply if that\n  // portion is `.` or `..`, which can be\n  // resolved away. Level 2 only takes other portions out of the\n  // middle of the path.\n  //\n  // A row of `**/x` then matches if the ** can walk the portions\n  // before the one that x matches, the same as #matchGlobstar. At\n  // level 2, this is only known if none of them are `.` or `..`, so\n  // that the path does not change when it is resolved.\n  #canMatch(f: string): 'no' | 'yes' | 'maybe' {\n    const sep: PathSeps =\n      !this.isWindows || !f.includes('\\\\') ? '/'\n      : f.includes('/') ? 'both'\n      : '\\\\'\n    // the portions that f.split(/\\/+/) would end with, and where they\n    // start in f, found when a row needs them. `ends` is 0 until they\n    // are found, then 1, or -1 if they can not be used.\n    let ends = this.#endCheck ? 0 : -1\n    let last = ''\n    let lastStart = 0\n    let prev: string | undefined\n    let prevStart = 0\n    const dot = !!this.options.dot\n    // A string compare is cheaper than includes(), and a Matcher test\n    // costs more, so the cheaper check goes first.\n    ROWS: for (let r = 0; r < this.set.length; r++) {\n      const row = this.set[r]!\n      const p = row[row.length - 1]\n      let end = ends !== -1 && this.#endRows[r]! && p !== GLOBSTAR\n      if (end && ends === 0) {\n        const i = lastSep(f, f.length, sep)\n        lastStart = i + 1\n        last = f.slice(lastStart)\n        if (last === '' && i >= 0) {\n          let j = i\n          while (j > 0 && isSep(f.charCodeAt(j - 1), sep)) j--\n          prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep) + 1\n          prev = f.slice(prevStart, j)\n        }\n        const resolves =\n          this.#level2 &&\n          (isDots(last) ||\n            (last === '' && prev !== undefined && isDots(prev)))\n        ends = resolves ? -1 : 1\n        end = !resolves\n      }\n      let tailStart = -1\n      if (end && typeof p === 'string') {\n        tailStart = endIndex(p, last, lastStart, prev, prevStart)\n        if (tailStart === -1) continue\n      }\n      if (this.#literalCheck) {\n        for (const l of this.#literals[r]!) {\n          if (!f.includes(l)) continue ROWS\n        }\n      }\n      if (end && typeof p === 'object') {\n        tailStart = endIndex(p, last, lastStart, prev, prevStart)\n        if (tailStart === -1) continue\n      }\n      const shape = this.#shapes[r]\n      if (shape === 'base' && end) return 'yes'\n      if (shape === 'tail' && end) {\n        if (this.#level2 && dotPortion(f, 0, tailStart, true, sep)) {\n          return 'maybe'\n        }\n        if (!dotPortion(f, 0, tailStart, dot, sep)) return 'yes'\n        continue\n      }\n      if (shape === 'mid' || shape === 'head') {\n        const m = this.#walk(f, row, shape === 'head', dot, sep)\n        if (m !== 'no') return m\n        continue\n      }\n      return 'maybe'\n    }\n    return 'no'\n  }\n\n  // Match a row of a known shape against the split path, the same as\n  // #matchGlobstar and #matchGlobStarBodySections do. None of these\n  // rows have a drive letter, so they start at the first portion.\n  #matchShape(\n    file: string[],\n    row: ParseReturnFiltered[],\n    shape: 'tail' | 'mid' | 'head',\n  ): boolean {\n    const dot = !!this.options.dot\n    const n = file.length\n    if (shape === 'head') {\n      // x, then at least one portion that ** can walk\n      if (n < 2 || !portionMatch(row[0] as string | Matcher, file[0]!)) {\n        return false\n      }\n      for (let i = 1; i < n; i++)\n        if (!walkable(file[i]!, dot)) return false\n      return true\n    }\n    const x = row[1] as string | Matcher\n    if (shape === 'tail') {\n      // x is the last portion, or the one before a trailing ''\n      let t = n - 1\n      if (!portionMatch(x, file[t]!)) {\n        if (file[t] !== '' || n === 1 || !portionMatch(x, file[--t]!)) {\n          return false\n        }\n      }\n      for (let i = 0; i < t; i++)\n        if (!walkable(file[i]!, dot)) return false\n      return true\n    }\n    // mid: the first x that ** can walk to, with a portion after it,\n    // and ** can walk all of those\n    for (let k = 0; k < n; k++) {\n      if (portionMatch(x, file[k]!) && k + 1 < n) {\n        let i = k + 1\n        while (i < n && walkable(file[i]!, dot)) i++\n        if (i === n) return true\n      }\n      if (!walkable(file[k]!, dot)) return false\n    }\n    return false\n  }\n\n  // Match a row of `**/x/**` or `x/**` against the path, the same as\n  // #matchGlobstar and #matchGlobStarBodySections do once it is split.\n  // x must match a portion (the first one, for `x/**`), the ** before\n  // it must be able to walk the portions before that one, and there\n  // must be a portion after it, which the ** after it can walk. At\n  // level 2, this is only known if no portion is `.` or `..`.\n  #walk(\n    f: string,\n    row: ParseReturnFiltered[],\n    head: boolean,\n    dot: boolean,\n    sep: PathSeps,\n  ): 'yes' | 'no' | 'maybe' {\n    if (this.#level2 && dotPortion(f, 0, f.length, true, sep))\n      return 'maybe'\n    const x = row[head ? 0 : 1] as string | Matcher\n    // the last portion has none after it, so it can not be x\n    let s = 0\n    for (let e = nextSep(f, s, sep); e !== -1; e = nextSep(f, s, sep)) {\n      // the start of the next portion\n      let next = e + 1\n      while (next < f.length && isSep(f.charCodeAt(next), sep)) next++\n      const hit =\n        typeof x === 'string' ?\n          e - s === x.length && f.startsWith(x, s)\n        : e > s && x.testUnchecked(f.slice(s, e))\n      if (hit && !dotPortion(f, next, f.length, dot, sep)) return 'yes'\n      if (head || dotPortion(f, s, next, dot, sep)) return 'no'\n      s = next\n    }\n    return 'no'\n  }\n\n  // the last split, if it was the same path with the same split\n  // settings\n  #cachedSplit(f: string) {\n    const last = lastSplit\n    return (\n        last?.f === f &&\n          last.isWindows === this.isWindows &&\n          last.preserveMultipleSlashes === this.preserveMultipleSlashes &&\n          last.normalize === this.#form\n      ) ?\n        last\n      : undefined\n  }\n\n  // split a path for match(), and keep the parts for the next call\n  #split(f: string) {\n    const { isWindows, preserveMultipleSlashes } = this\n    // windows: need to use /, not \\\n    let parts = this.#slashSplit(isWindows ? f.split('\\\\').join('/') : f)\n    // normalize each portion, so that a char that normalizes to `/`\n    // does not make a new portion\n    const normalize = this.#form\n    if (normalize) parts = parts.map(p => p.normalize(normalize))\n    lastSplit = {\n      f,\n      isWindows,\n      preserveMultipleSlashes,\n      normalize,\n      parts,\n    }\n    return lastSplit\n  }\n\n  // resolve `.` and `..` portions of a path, for level 2\n  #levelTwoFileOptimize(file: string[]) {\n    // work on a copy, so that the cached parts do not change\n    const parts = [...file]\n    let didSomething: boolean = false\n\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      // .. can not remove the root of a Windows path\n      const root = this.#rootIndex(parts) + 1\n      let dd: number = root\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd = Math.max(dd - 2, root)\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    // each **/.. split doubles the patterns, and adds a copy of the\n    // whole pattern. Throw if either gets too large. A partial split\n    // would match some paths and not others, depending on which rows\n    // the pass reached first.\n    const { braceExpandMax = DEFAULT_BRACE_EXPAND_MAX } = this.options\n    let splitCells = 0\n    const maxSplitCells = 1_000_000\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          // Check before changing parts or allocating the new row.\n          const addedCells = parts.length - 1\n          if (\n            globParts.length >= braceExpandMax ||\n            splitCells + addedCells > maxSplitCells\n          ) {\n            throw new RangeError(\n              `optimizationLevel 2: too many patterns from '**/..'`,\n            )\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          splitCells += addedCells\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        // .. can not remove the root of a Windows path\n        const root = this.#rootIndex(parts) + 1\n        let dd: number = root\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd = Math.max(dd - 2, root)\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/,
/} -> 
/\n  // {
/*/,
/

/} ->

/*/\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    const keys = new Set()\n    const rows = globParts.filter(parts => {\n      const key = parts.join('/')\n      if (keys.has(key)) return false\n      keys.add(key)\n      return true\n    })\n\n    // A row is covered by another row that has `*` at some positions,\n    // and is the same at all others. Collect each distinct set of `*`\n    // positions, then look up each row with `*` put at those positions.\n    const stars = new Map()\n    for (const parts of rows) {\n      const s: number[] = []\n      for (let i = 0; i < parts.length; i++) {\n        if (parts[i] === '*') s.push(i)\n      }\n      if (s.length) stars.set(s.join(','), s)\n    }\n    // Each row is checked against each set of `*` positions, so skip\n    // this if there are too many. The patterns match the same paths\n    // either way.\n    if (!stars.size || rows.length * stars.size > 100_000) return rows\n\n    const { dot } = this.options\n    return rows.filter(parts => {\n      for (const s of stars.values()) {\n        if (s[s.length - 1]! >= parts.length) continue\n        const c = [...parts]\n        let ok = true\n        let changed = false\n        for (const i of s) {\n          const p = parts[i]!\n          if (p === '*') continue\n          if (!p || p === '**' || (!dot && p.startsWith('.'))) {\n            ok = false\n            break\n          }\n          c[i] = '*'\n          changed = true\n        }\n        if (ok && changed && keys.has(c.join('/'))) return false\n      }\n      return true\n    })\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // Match the parts of a path against one row of the set. `resolved`\n  // is the parts after level 2 resolves `.` and `..` in them, or the\n  // same parts below level 2. Set partial to true to test if, for\n  // example, \"/a/b\" matches the start of \"/*/b/*/d\". Partial means, if\n  // you run out of file before you run out of pattern, then that's\n  // fine, as long as all the parts match.\n  #matchRow(\n    file: string[],\n    resolved: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n  ) {\n    let fileStartIndex = 0\n    let patternStartIndex = 0\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa, and\n    // //?/UNC/host/share/... can match //host/share/... and vice versa.\n    // Drive letters in absolute drive or unc paths, and the host and\n    // share of UNC paths, are always compared case-insensitively.\n    const fh = this.isWindows ? uncHost(resolved) : -1\n    const ph = fh === -1 ? -1 : uncHost(pattern)\n    if (ph !== -1) {\n      const host = pattern[ph]\n      const share = pattern[ph + 1]\n      if (typeof host !== 'string' || typeof share !== 'string') {\n        // a host or share with magic is matched as usual\n        fileStartIndex = fh\n        patternStartIndex = ph\n      } else if (\n        resolved[fh]!.toLowerCase() === host.toLowerCase() &&\n        resolved[fh + 1]!.toLowerCase() === share.toLowerCase()\n      ) {\n        fileStartIndex = fh + 2\n        patternStartIndex = ph + 2\n      }\n    } else if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi =\n        fileUNC ? 3\n        : fileDrive ? 0\n        : undefined\n      const pdi =\n        patternUNC ? 3\n        : patternDrive ? 0\n        : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        // the drives match, so start matching after them\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          patternStartIndex = pdi + 1\n          fileStartIndex = fdi + 1\n        }\n      }\n    }\n\n    // the drive letters are found in the parts before level 2 resolves\n    // them, and the match uses the resolved parts\n    file = resolved\n\n    if (pattern.includes(GLOBSTAR)) {\n      return this.#matchGlobstar(\n        file,\n        pattern,\n        partial,\n        fileStartIndex,\n        patternStartIndex,\n      )\n    }\n\n    return this.#matchOne(\n      file,\n      pattern,\n      partial,\n      fileStartIndex,\n      patternStartIndex,\n    )\n  }\n\n  #matchGlobstar(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n  ) {\n    const { head, body, tail, segments } = this.#getGlobstarParts(\n      pattern,\n      partial,\n      patternIndex,\n    )\n\n    // check the head, from the current file/pattern index.\n    if (head.length) {\n      const headEnd = fileIndex + head.length\n      if (!this.#matchOne(file, head, partial, fileIndex, 0, headEnd)) {\n        return false\n      }\n      fileIndex += head.length\n      patternIndex += head.length\n    }\n    // now we know the head matches!\n\n    // if the last portion is not empty, it MUST match the end\n    // check the tail\n    let fileTailMatch: number = 0\n    if (tail.length) {\n      // if head + tail > file, then we cannot possibly match\n      if (tail.length + fileIndex > file.length) return false\n\n      // try to match the tail\n      let tailStart = file.length - tail.length\n      if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n        fileTailMatch = tail.length\n      } else {\n        // affordance for stuff like a/**/* matching a/b/\n        // if the last file portion is '', and there's more to the pattern\n        // then try without the '' bit.\n        if (\n          file[file.length - 1] !== '' ||\n          fileIndex + tail.length === file.length\n        ) {\n          return false\n        }\n        tailStart--\n        if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n          return false\n        }\n        fileTailMatch = tail.length + 1\n      }\n    }\n\n    // now we know the tail matches!\n\n    // the middle is zero or more portions wrapped in **, possibly\n    // containing more ** sections.\n    // so a/**/b/**/c/**/d has become **/b/**/c/**\n    // if it's empty, it means a/**/b, just verify we have no bad dots\n    // if there's no tail, so it ends on /**, then we must have *something*\n    // after the head, or it's not a matc\n    if (!body.length) {\n      let sawSome = !!fileTailMatch\n      for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n        const f = String(file[i])\n        sawSome = true\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      // in partial mode, we just need to get past all file parts\n      return partial || sawSome\n    }\n\n    // now we know that there's one or more body sections, which can\n    // be matched anywhere from the 0 index (because the head was pruned)\n    // through to the length-fileTailMatch index.\n    return !!this.#matchGlobStarBodySections(\n      file,\n      segments,\n      file.length - fileTailMatch,\n      fileIndex,\n      0,\n      partial,\n      0,\n      !!fileTailMatch,\n      new Set(),\n    )\n  }\n\n  // Split the pattern into head, tail, and middle of ** delimited\n  // parts. The tail has to be at the end, and the others just have to\n  // be found in order from the head. These only depend on the pattern\n  // row, so they are kept for the next path.\n  #getGlobstarParts(\n    pattern: ParseReturn[],\n    partial: boolean,\n    patternIndex: number,\n  ): GlobstarParts {\n    let byStart = this.#globstarParts.get(pattern)\n    if (!byStart) {\n      byStart = []\n      this.#globstarParts.set(pattern, byStart)\n    }\n    const key = patternIndex * 2 + (partial ? 1 : 0)\n    const found = byStart[key]\n    if (found) return found\n\n    const firstgs = pattern.indexOf(GLOBSTAR, patternIndex)\n    const lastgs = pattern.lastIndexOf(GLOBSTAR)\n    const head = pattern.slice(patternIndex, firstgs)\n    const body = pattern.slice(firstgs + 1, partial ? undefined : lastgs)\n    const tail = partial ? [] : pattern.slice(lastgs + 1)\n\n    // split the body up into sections, and note the number of\n    // portions that must come after the start of each one\n    const segments: [ParseReturn[], number][] = [[[], 0]]\n    let current = segments[0]!\n    let nonGsParts = 0\n    const nonGsPartsSums: number[] = [0]\n    for (const b of body) {\n      if (b === GLOBSTAR) {\n        nonGsPartsSums.push(nonGsParts)\n        current = [[], 0]\n        segments.push(current)\n      } else {\n        current[0].push(b)\n        nonGsParts++\n      }\n    }\n    // the portions in this section and the ones after it\n    segments.forEach((b, i) => {\n      b[1] = nonGsParts - (nonGsPartsSums[i] as number)\n    })\n\n    const parts = { head, body, tail, segments }\n    byStart[key] = parts\n    return parts\n  }\n\n  // return false for \"nope, not matching\"\n  // return null for \"not matching, cannot keep trying\"\n  #matchGlobStarBodySections(\n    file: string[],\n    // pattern section, and the portions that it and the rest need\n    bodySegments: [ParseReturn[], number][],\n    // the end of the file portions that the body can match\n    fileLength: number,\n    fileIndex: number,\n    bodyIndex: number,\n    partial: boolean,\n    globStarDepth: number,\n    sawTail: boolean,\n    // the places that a walk has already tried, as\n    // bodyIndex * (file.length + 1) + fileIndex. A walk from a place\n    // does the same no matter how it got there, and it only comes back\n    // if it found no match, so a walk that gets to one stops.\n    tried: Set,\n  ): boolean | null {\n    // take the first body segment, and walk from fileIndex to its \"after\"\n    // value at the end\n    // If it doesn't match at that position, we increment, until we hit\n    // that final possible position, and give up.\n    // If it does match, then advance and try to rest.\n    // If any of them fail we keep walking forward.\n    // this is still a bit recursively painful, but it's more constrained\n    // than previous implementations, because we never test something that\n    // can't possibly be a valid matching condition.\n    const bs = bodySegments[bodyIndex]\n    if (!bs) {\n      // with partial, the body is the rest of the pattern, so it\n      // matches if no portions are left, or only the '' of a trailing\n      // / (as a/* matches a/b/). A ** at the end walks them as its own\n      // empty section.\n      if (partial) {\n        return (\n          fileIndex >= fileLength ||\n          (fileIndex === fileLength - 1 && file[fileIndex] === '')\n        )\n      }\n      // just make sure that there's no bad dots before the tail\n      for (let i = fileIndex; i < fileLength; i++) {\n        sawTail = true\n        const f = file[i]\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      return sawTail\n    }\n\n    // have a non-globstar body section to test, up to the last index\n    // where it can start\n    const [body, need] = bs\n    // with partial, the path can end before the body does\n    const after = partial ? fileLength : fileLength - need\n    while (fileIndex <= after) {\n      const key = bodyIndex * (file.length + 1) + fileIndex\n      if (tried.has(key)) return false\n      tried.add(key)\n      const m = this.#matchOne(\n        file,\n        body,\n        partial,\n        fileIndex,\n        0,\n        fileIndex + body.length,\n      )\n      // if limit exceeded, no match. intentional false negative,\n      // acceptable break in correctness for security.\n      if (m && globStarDepth < this.maxGlobstarRecursion) {\n        // match! see if the rest match. if so, we're done!\n        const sub = this.#matchGlobStarBodySections(\n          file,\n          bodySegments,\n          fileLength,\n          fileIndex + body.length,\n          bodyIndex + 1,\n          partial,\n          globStarDepth + 1,\n          sawTail,\n          tried,\n        )\n        if (sub !== false) {\n          return sub\n        }\n      }\n      // the ** does not walk past the last place the body can start\n      if (fileIndex === after) break\n      const f = file[fileIndex]!\n      if (\n        f === '.' ||\n        f === '..' ||\n        (!this.options.dot && f.startsWith('.'))\n      ) {\n        return false\n      }\n\n      fileIndex++\n    }\n    // walked off. no point continuing\n    return partial || null\n  }\n\n  #matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n    // only match the file portions before this index\n    fileEnd: number = file.length,\n  ) {\n    let fi: number\n    let pi: number\n    let pl: number\n    let fl: number\n    for (\n      fi = fileIndex,\n        pi = patternIndex,\n        fl = Math.min(fileEnd, file.length),\n        pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      let p = pattern[pi]\n      let f = file[fi]\n\n      // should be impossible.\n      /* c8 ignore start */\n      if (p === false || p === GLOBSTAR) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into Matchers.\n      if (!portionMatch(p, f)) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though * can match \"\", except in\n    // partial mode, where it might simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  // Expand braces, except numeric ranges such as {0..999} with at\n  // least RANGE_MIN values. Each of those stays in its pattern as\n  // `0..999`, for the Matcher to test. If a range might\n  // be inside a [...] class, expand all of them instead.\n  #expandBraces(): string[] {\n    const { pattern } = this\n    if (this.options.nobrace) return this.braceExpand()\n    let code = 0xe000\n    while (pattern.includes(String.fromCharCode(code))) {\n      if (++code > 0xf8ff) return this.braceExpand()\n    }\n    const mark = String.fromCharCode(code)\n    let found = false\n    const marked = pattern.replace(\n      rangeRe,\n      (m, lo: string, hi: string) => {\n        const a = Number(lo)\n        const b = Number(hi)\n        if (\n          !Number.isSafeInteger(a) ||\n          !Number.isSafeInteger(b) ||\n          Math.abs(a - b) + 1 < RANGE_MIN\n        ) {\n          return m\n        }\n        found = true\n        return `${mark}${lo}..${hi}${mark}`\n      },\n    )\n    if (!found) return this.braceExpand()\n    const set = braceExpand(marked, this.options)\n    for (const p of set) {\n      for (const portion of p.split('/')) {\n        const c = portion.indexOf('[')\n        if (c !== -1 && c < portion.lastIndexOf(mark)) {\n          return this.braceExpand()\n        }\n        if (!this.options.noext && inRepeatOrNegExt(portion, mark)) {\n          return this.braceExpand()\n        }\n      }\n    }\n    this.#rangeMark = mark\n    return set\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    const {\n      nocase,\n      nocaseMagicOnly,\n      noext = false,\n      dot,\n      normalize,\n    } = options\n    const rangeMark = this.#rangeMark\n    const lit =\n      rangeMark && pattern.includes(rangeMark) ?\n        undefined\n      : literal(pattern, noext)\n    // in nocase mode, a literal with cased chars still needs a\n    // Matcher, unless nocaseMagicOnly is set.\n    if (\n      lit !== undefined &&\n      !(\n        nocase &&\n        !nocaseMagicOnly &&\n        pattern.toUpperCase() !== pattern.toLowerCase()\n      )\n    ) {\n      return this.#norm(lit)\n    }\n\n    if (this.#pending) return PENDING\n    let m = this.#matchers.get(pattern)\n    if (!m) {\n      if (!noext) assertValidExtglobs(pattern)\n      m = new Matcher(pattern, {\n        nocase,\n        noext,\n        dot,\n        normalize,\n        ...(rangeMark && { rangeMark }),\n      })\n      this.#matchers.set(pattern, m)\n    }\n    return m\n  }\n\n  #slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // treat the test path as a set of pathparts. If it was not just\n    // split or checked, check that it can match before splitting it.\n    let split = this.#cachedSplit(f)\n    if (!split) {\n      // the checks look at the path as given, so not if it is\n      // normalized\n      if (\n        !partial &&\n        !this.#form &&\n        (this.#endCheck || this.#literalCheck) &&\n        lastChecked !== f\n      ) {\n        lastChecked = f\n        const can = this.#canMatch(f)\n        if (can === 'no') return options.flipNegate ? false : this.negate\n        if (can === 'yes') return options.flipNegate ? true : !this.negate\n      }\n      split = this.#split(f)\n    }\n    const ff = split.parts\n    // the parts after level 2 resolves them, kept for the next pattern\n    // that tests the same path\n    const resolved =\n      this.#level2 ?\n        (split.resolved ??= this.#levelTwoFileOptimize(ff))\n      : ff\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let r = 0; r < set.length; r++) {\n      const pattern = set[r]!\n      const shape = partial ? undefined : this.#shapes[r]\n      // level 2 does not change a path of one portion\n      const hit =\n        shape === 'base' ?\n          portionMatch(pattern[0] as string | Matcher, filename)\n        : shape ? this.#matchShape(resolved, pattern, shape)\n        : options.matchBase && pattern.length === 1 ?\n          this.#matchRow([filename], [filename], pattern, partial)\n        : this.#matchRow(ff, resolved, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\nexport type { Form }\n/* c8 ignore stop */\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.d.ts.map
index 09d6eab4e6502cde5495bf5ea51637d6db86999c..4894097546c9b5612a694256a79c2a39919f09af 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.d.ts.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;;;;;;;;GAkBG;AAEH,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAczE,CAAA"}
\ No newline at end of file
+{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;;;;;;;;GAkBG;AAEH,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,KACvE,MAmBF,CAAA"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.js b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.js
index ad648fba64d40d27684d091b66282f0bbeb27012..30bdd481dc5de3069cd7504bf7cc05952fb17459 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.js
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.js
@@ -21,6 +21,10 @@ exports.unescape = void 0;
  * unescaped.
  */
 const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
+    // escape() writes a leading '!' as '@(!)' in windowsPathsNoEscape mode
+    if (windowsPathsNoEscape && s.startsWith('@(!)')) {
+        return ('!' + (0, exports.unescape)(s.slice(4), { windowsPathsNoEscape, magicalBraces }));
+    }
     if (magicalBraces) {
         return windowsPathsNoEscape ?
             s.replace(/\[([^/\\])\]/g, '$1')
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.js.map
index 44387ec58d1bb4950d2869a3c65ff08738fd79ad..3ebabca26071c08dbda37cb7cab98aebbb1b1c49 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.js.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/commonjs/unescape.js.map
@@ -1 +1 @@
-{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEI,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,IAAI,MACgD,EAAE,EACxE,EAAE;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;YAClC,CAAC,CAAC,CAAC;iBACE,OAAO,CAAC,0BAA0B,EAAE,MAAM,CAAC;iBAC3C,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,iBAAiB,EAAE,IAAI,CAAC;QACpC,CAAC,CAAC,CAAC;aACE,OAAO,CAAC,4BAA4B,EAAE,MAAM,CAAC;aAC7C,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAnBY,QAAA,QAAQ,YAmBpB","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = true,\n  }: Pick = {},\n) => {\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/\\[([^/\\\\])\\]/g, '$1')\n      : s\n          .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n          .replace(/\\\\([^/])/g, '$1')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n    : s\n        .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n        .replace(/\\\\([^/{}])/g, '$1')\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEI,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,IAAI,MACgD,EAAE,EAChE,EAAE;IACV,uEAAuE;IACvE,IAAI,oBAAoB,IAAI,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;QACjD,OAAO,CACL,GAAG,GAAG,IAAA,gBAAQ,EAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,oBAAoB,EAAE,aAAa,EAAE,CAAC,CACpE,CAAA;IACH,CAAC;IACD,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;YAClC,CAAC,CAAC,CAAC;iBACE,OAAO,CAAC,0BAA0B,EAAE,MAAM,CAAC;iBAC3C,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,iBAAiB,EAAE,IAAI,CAAC;QACpC,CAAC,CAAC,CAAC;aACE,OAAO,CAAC,4BAA4B,EAAE,MAAM,CAAC;aAC7C,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAzBY,QAAA,QAAQ,YAyBpB","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = true,\n  }: Pick = {},\n): string => {\n  // escape() writes a leading '!' as '@(!)' in windowsPathsNoEscape mode\n  if (windowsPathsNoEscape && s.startsWith('@(!)')) {\n    return (\n      '!' + unescape(s.slice(4), { windowsPathsNoEscape, magicalBraces })\n    )\n  }\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/\\[([^/\\\\])\\]/g, '$1')\n      : s\n          .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n          .replace(/\\\\([^/])/g, '$1')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n    : s\n        .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n        .replace(/\\\\([^/{}])/g, '$1')\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.d.ts b/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.d.ts
deleted file mode 100644
index 74f2cf9322b97504fa4d6eb29dbe74222a4449ba..0000000000000000000000000000000000000000
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.d.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { MinimatchOptions, MMRegExp } from './index.js';
-export type ExtglobType = '!' | '?' | '+' | '*' | '@';
-export declare class AST {
-    #private;
-    type: ExtglobType | null;
-    id: number;
-    get depth(): number;
-    constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
-    get hasMagic(): boolean | undefined;
-    toString(): string;
-    push(...parts: (string | AST)[]): void;
-    toJSON(): unknown[];
-    isStart(): boolean;
-    isEnd(): boolean;
-    copyIn(part: AST | string): void;
-    clone(parent: AST): AST;
-    static fromGlob(pattern: string, options?: MinimatchOptions): AST;
-    toMMPattern(): MMRegExp | string;
-    get options(): MinimatchOptions;
-    toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
-}
-//# sourceMappingURL=ast.d.ts.map
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.d.ts.map
deleted file mode 100644
index 8965fd6a99ff91e22cd5de1f2c41563a673b8dc0..0000000000000000000000000000000000000000
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.d.ts.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwC5D,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAgJrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;IAexB,EAAE,SAAO;IAET,IAAI,KAAK,IAAI,MAAM,CAElB;gBAgBC,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IAkDlB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAe/B,MAAM;IAkBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsQjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CA6OjE"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.js b/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.js
deleted file mode 100644
index f639546593db64ee620281cffd819f3c103fc09b..0000000000000000000000000000000000000000
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.js
+++ /dev/null
@@ -1,841 +0,0 @@
-// parse a single path portion
-var _a;
-import { parseClass } from './brace-expressions.js';
-import { unescape } from './unescape.js';
-const types = new Set(['!', '?', '+', '*', '@']);
-const isExtglobType = (c) => types.has(c);
-const isExtglobAST = (c) => isExtglobType(c.type);
-// Map of which extglob types can adopt the children of a nested extglob
-//
-// anything but ! can adopt a matching type:
-// +(a|+(b|c)|d) => +(a|b|c|d)
-// *(a|*(b|c)|d) => *(a|b|c|d)
-// @(a|@(b|c)|d) => @(a|b|c|d)
-// ?(a|?(b|c)|d) => ?(a|b|c|d)
-//
-// * can adopt anything, because 0 or repetition is allowed
-// *(a|?(b|c)|d) => *(a|b|c|d)
-// *(a|+(b|c)|d) => *(a|b|c|d)
-// *(a|@(b|c)|d) => *(a|b|c|d)
-//
-// + can adopt @, because 1 or repetition is allowed
-// +(a|@(b|c)|d) => +(a|b|c|d)
-//
-// + and @ CANNOT adopt *, because 0 would be allowed
-// +(a|*(b|c)|d) => would match "", on *(b|c)
-// @(a|*(b|c)|d) => would match "", on *(b|c)
-//
-// + and @ CANNOT adopt ?, because 0 would be allowed
-// +(a|?(b|c)|d) => would match "", on ?(b|c)
-// @(a|?(b|c)|d) => would match "", on ?(b|c)
-//
-// ? can adopt @, because 0 or 1 is allowed
-// ?(a|@(b|c)|d) => ?(a|b|c|d)
-//
-// ? and @ CANNOT adopt * or +, because >1 would be allowed
-// ?(a|*(b|c)|d) => would match bbb on *(b|c)
-// @(a|*(b|c)|d) => would match bbb on *(b|c)
-// ?(a|+(b|c)|d) => would match bbb on +(b|c)
-// @(a|+(b|c)|d) => would match bbb on +(b|c)
-//
-// ! CANNOT adopt ! (nothing else can either)
-// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
-//
-// ! can adopt @
-// !(a|@(b|c)|d) => !(a|b|c|d)
-//
-// ! CANNOT adopt *
-// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
-//
-// ! CANNOT adopt +
-// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
-//
-// ! CANNOT adopt ?
-// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
-const adoptionMap = new Map([
-    ['!', ['@']],
-    ['?', ['?', '@']],
-    ['@', ['@']],
-    ['*', ['*', '+', '?', '@']],
-    ['+', ['+', '@']],
-]);
-// nested extglobs that can be adopted in, but with the addition of
-// a blank '' element.
-const adoptionWithSpaceMap = new Map([
-    ['!', ['?']],
-    ['@', ['?']],
-    ['+', ['?', '*']],
-]);
-// union of the previous two maps
-const adoptionAnyMap = new Map([
-    ['!', ['?', '@']],
-    ['?', ['?', '@']],
-    ['@', ['?', '@']],
-    ['*', ['*', '+', '?', '@']],
-    ['+', ['+', '@', '?', '*']],
-]);
-// Extglobs that can take over their parent if they are the only child
-// the key is parent, value maps child to resulting extglob parent type
-// '@' is omitted because it's a special case. An `@` extglob with a single
-// member can always be usurped by that subpattern.
-const usurpMap = new Map([
-    ['!', new Map([['!', '@']])],
-    [
-        '?',
-        new Map([
-            ['*', '*'],
-            ['+', '*'],
-        ]),
-    ],
-    [
-        '@',
-        new Map([
-            ['!', '!'],
-            ['?', '?'],
-            ['@', '@'],
-            ['*', '*'],
-            ['+', '+'],
-        ]),
-    ],
-    [
-        '+',
-        new Map([
-            ['?', '*'],
-            ['*', '*'],
-        ]),
-    ],
-]);
-// Patterns that get prepended to bind to the start of either the
-// entire string, or just a single path portion, to prevent dots
-// and/or traversal patterns, when needed.
-// Exts don't need the ^ or / bit, because the root binds that already.
-const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
-const startNoDot = '(?!\\.)';
-// characters that indicate a start of pattern needs the "no dots" bit,
-// because a dot *might* be matched. ( is not in the list, because in
-// the case of a child extglob, it will handle the prevention itself.
-const addPatternStart = new Set(['[', '.']);
-// cases where traversal is A-OK, no dot prevention needed
-const justDots = new Set(['..', '.']);
-const reSpecials = new Set('().*{}+?[]^$\\!');
-const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-// any single thing other than /
-const qmark = '[^/]';
-// * => any number of characters
-const star = qmark + '*?';
-// use + when we need to ensure that *something* matches, because the * is
-// the only thing in the path portion.
-const starNoEmpty = qmark + '+?';
-// remove the \ chars that we added if we end up doing a nonmagic compare
-// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
-let ID = 0;
-export class AST {
-    type;
-    #root;
-    #hasMagic;
-    #uflag = false;
-    #parts = [];
-    #parent;
-    #parentIndex;
-    #negs;
-    #filledNegs = false;
-    #options;
-    #toString;
-    // set to true if it's an extglob with no children
-    // (which really means one child of '')
-    #emptyExt = false;
-    id = ++ID;
-    get depth() {
-        return (this.#parent?.depth ?? -1) + 1;
-    }
-    [Symbol.for('nodejs.util.inspect.custom')]() {
-        return {
-            '@@type': 'AST',
-            id: this.id,
-            type: this.type,
-            root: this.#root.id,
-            parent: this.#parent?.id,
-            depth: this.depth,
-            partsLength: this.#parts.length,
-            parts: this.#parts,
-        };
-    }
-    constructor(type, parent, options = {}) {
-        this.type = type;
-        // extglobs are inherently magical
-        if (type)
-            this.#hasMagic = true;
-        this.#parent = parent;
-        this.#root = this.#parent ? this.#parent.#root : this;
-        this.#options = this.#root === this ? options : this.#root.#options;
-        this.#negs = this.#root === this ? [] : this.#root.#negs;
-        if (type === '!' && !this.#root.#filledNegs)
-            this.#negs.push(this);
-        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
-    }
-    get hasMagic() {
-        /* c8 ignore start */
-        if (this.#hasMagic !== undefined)
-            return this.#hasMagic;
-        /* c8 ignore stop */
-        for (const p of this.#parts) {
-            if (typeof p === 'string')
-                continue;
-            if (p.type || p.hasMagic)
-                return (this.#hasMagic = true);
-        }
-        // note: will be undefined until we generate the regexp src and find out
-        return this.#hasMagic;
-    }
-    // reconstructs the pattern
-    toString() {
-        return (this.#toString !== undefined ? this.#toString
-            : !this.type ?
-                (this.#toString = this.#parts.map(p => String(p)).join(''))
-                : (this.#toString =
-                    this.type +
-                        '(' +
-                        this.#parts.map(p => String(p)).join('|') +
-                        ')'));
-    }
-    #fillNegs() {
-        /* c8 ignore start */
-        if (this !== this.#root)
-            throw new Error('should only call on root');
-        if (this.#filledNegs)
-            return this;
-        /* c8 ignore stop */
-        // call toString() once to fill this out
-        this.toString();
-        this.#filledNegs = true;
-        let n;
-        while ((n = this.#negs.pop())) {
-            if (n.type !== '!')
-                continue;
-            // walk up the tree, appending everthing that comes AFTER parentIndex
-            let p = n;
-            let pp = p.#parent;
-            while (pp) {
-                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
-                    for (const part of n.#parts) {
-                        /* c8 ignore start */
-                        if (typeof part === 'string') {
-                            throw new Error('string part in extglob AST??');
-                        }
-                        /* c8 ignore stop */
-                        part.copyIn(pp.#parts[i]);
-                    }
-                }
-                p = pp;
-                pp = p.#parent;
-            }
-        }
-        return this;
-    }
-    push(...parts) {
-        for (const p of parts) {
-            if (p === '')
-                continue;
-            /* c8 ignore start */
-            if (typeof p !== 'string' &&
-                !(p instanceof _a && p.#parent === this)) {
-                throw new Error('invalid part: ' + p);
-            }
-            /* c8 ignore stop */
-            this.#parts.push(p);
-        }
-    }
-    toJSON() {
-        const ret = this.type === null ?
-            this.#parts
-                .slice()
-                .map(p => (typeof p === 'string' ? p : p.toJSON()))
-            : [this.type, ...this.#parts.map(p => p.toJSON())];
-        if (this.isStart() && !this.type)
-            ret.unshift([]);
-        if (this.isEnd() &&
-            (this === this.#root ||
-                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
-            ret.push({});
-        }
-        return ret;
-    }
-    isStart() {
-        if (this.#root === this)
-            return true;
-        // if (this.type) return !!this.#parent?.isStart()
-        if (!this.#parent?.isStart())
-            return false;
-        if (this.#parentIndex === 0)
-            return true;
-        // if everything AHEAD of this is a negation, then it's still the "start"
-        const p = this.#parent;
-        for (let i = 0; i < this.#parentIndex; i++) {
-            const pp = p.#parts[i];
-            if (!(pp instanceof _a && pp.type === '!')) {
-                return false;
-            }
-        }
-        return true;
-    }
-    isEnd() {
-        if (this.#root === this)
-            return true;
-        if (this.#parent?.type === '!')
-            return true;
-        if (!this.#parent?.isEnd())
-            return false;
-        if (!this.type)
-            return this.#parent?.isEnd();
-        // if not root, it'll always have a parent
-        /* c8 ignore start */
-        const pl = this.#parent ? this.#parent.#parts.length : 0;
-        /* c8 ignore stop */
-        return this.#parentIndex === pl - 1;
-    }
-    copyIn(part) {
-        if (typeof part === 'string')
-            this.push(part);
-        else
-            this.push(part.clone(this));
-    }
-    clone(parent) {
-        const c = new _a(this.type, parent);
-        for (const p of this.#parts) {
-            c.copyIn(p);
-        }
-        return c;
-    }
-    static #parseAST(str, ast, pos, opt, extDepth) {
-        const maxDepth = opt.maxExtglobRecursion ?? 2;
-        let escaping = false;
-        let inBrace = false;
-        let braceStart = -1;
-        let braceNeg = false;
-        if (ast.type === null) {
-            // outside of a extglob, append until we find a start
-            let i = pos;
-            let acc = '';
-            while (i < str.length) {
-                const c = str.charAt(i++);
-                // still accumulate escapes at this point, but we do ignore
-                // starts that are escaped
-                if (escaping || c === '\\') {
-                    escaping = !escaping;
-                    acc += c;
-                    continue;
-                }
-                if (inBrace) {
-                    if (i === braceStart + 1) {
-                        if (c === '^' || c === '!') {
-                            braceNeg = true;
-                        }
-                    }
-                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
-                        inBrace = false;
-                    }
-                    acc += c;
-                    continue;
-                }
-                else if (c === '[') {
-                    inBrace = true;
-                    braceStart = i;
-                    braceNeg = false;
-                    acc += c;
-                    continue;
-                }
-                // we don't have to check for adoption here, because that's
-                // done at the other recursion point.
-                const doRecurse = !opt.noext &&
-                    isExtglobType(c) &&
-                    str.charAt(i) === '(' &&
-                    extDepth <= maxDepth;
-                if (doRecurse) {
-                    ast.push(acc);
-                    acc = '';
-                    const ext = new _a(c, ast);
-                    i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
-                    ast.push(ext);
-                    continue;
-                }
-                acc += c;
-            }
-            ast.push(acc);
-            return i;
-        }
-        // some kind of extglob, pos is at the (
-        // find the next | or )
-        let i = pos + 1;
-        let part = new _a(null, ast);
-        const parts = [];
-        let acc = '';
-        while (i < str.length) {
-            const c = str.charAt(i++);
-            // still accumulate escapes at this point, but we do ignore
-            // starts that are escaped
-            if (escaping || c === '\\') {
-                escaping = !escaping;
-                acc += c;
-                continue;
-            }
-            if (inBrace) {
-                if (i === braceStart + 1) {
-                    if (c === '^' || c === '!') {
-                        braceNeg = true;
-                    }
-                }
-                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
-                    inBrace = false;
-                }
-                acc += c;
-                continue;
-            }
-            else if (c === '[') {
-                inBrace = true;
-                braceStart = i;
-                braceNeg = false;
-                acc += c;
-                continue;
-            }
-            const doRecurse = !opt.noext &&
-                isExtglobType(c) &&
-                str.charAt(i) === '(' &&
-                /* c8 ignore start - the maxDepth is sufficient here */
-                (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
-            /* c8 ignore stop */
-            if (doRecurse) {
-                const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
-                part.push(acc);
-                acc = '';
-                const ext = new _a(c, part);
-                part.push(ext);
-                i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
-                continue;
-            }
-            if (c === '|') {
-                part.push(acc);
-                acc = '';
-                parts.push(part);
-                part = new _a(null, ast);
-                continue;
-            }
-            if (c === ')') {
-                if (acc === '' && ast.#parts.length === 0) {
-                    ast.#emptyExt = true;
-                }
-                part.push(acc);
-                acc = '';
-                ast.push(...parts, part);
-                return i;
-            }
-            acc += c;
-        }
-        // unfinished extglob
-        // if we got here, it was a malformed extglob! not an extglob, but
-        // maybe something else in there.
-        ast.type = null;
-        ast.#hasMagic = undefined;
-        ast.#parts = [str.substring(pos - 1)];
-        return i;
-    }
-    #canAdoptWithSpace(child) {
-        return this.#canAdopt(child, adoptionWithSpaceMap);
-    }
-    #canAdopt(child, map = adoptionMap) {
-        if (!child ||
-            typeof child !== 'object' ||
-            child.type !== null ||
-            child.#parts.length !== 1 ||
-            this.type === null) {
-            return false;
-        }
-        const gc = child.#parts[0];
-        if (!gc || typeof gc !== 'object' || gc.type === null) {
-            return false;
-        }
-        return this.#canAdoptType(gc.type, map);
-    }
-    #canAdoptType(c, map = adoptionAnyMap) {
-        return !!map.get(this.type)?.includes(c);
-    }
-    #adoptWithSpace(child, index) {
-        const gc = child.#parts[0];
-        const blank = new _a(null, gc, this.options);
-        blank.#parts.push('');
-        gc.push(blank);
-        this.#adopt(child, index);
-    }
-    #adopt(child, index) {
-        const gc = child.#parts[0];
-        this.#parts.splice(index, 1, ...gc.#parts);
-        for (const p of gc.#parts) {
-            if (typeof p === 'object')
-                p.#parent = this;
-        }
-        this.#toString = undefined;
-    }
-    #canUsurpType(c) {
-        const m = usurpMap.get(this.type);
-        return !!m?.has(c);
-    }
-    #canUsurp(child) {
-        if (!child ||
-            typeof child !== 'object' ||
-            child.type !== null ||
-            child.#parts.length !== 1 ||
-            this.type === null ||
-            this.#parts.length !== 1) {
-            return false;
-        }
-        const gc = child.#parts[0];
-        if (!gc || typeof gc !== 'object' || gc.type === null) {
-            return false;
-        }
-        return this.#canUsurpType(gc.type);
-    }
-    #usurp(child) {
-        const m = usurpMap.get(this.type);
-        const gc = child.#parts[0];
-        const nt = m?.get(gc.type);
-        /* c8 ignore start - impossible */
-        if (!nt)
-            return false;
-        /* c8 ignore stop */
-        this.#parts = gc.#parts;
-        for (const p of this.#parts) {
-            if (typeof p === 'object') {
-                p.#parent = this;
-            }
-        }
-        this.type = nt;
-        this.#toString = undefined;
-        this.#emptyExt = false;
-    }
-    static fromGlob(pattern, options = {}) {
-        const ast = new _a(null, undefined, options);
-        _a.#parseAST(pattern, ast, 0, options, 0);
-        return ast;
-    }
-    // returns the regular expression if there's magic, or the unescaped
-    // string if not.
-    toMMPattern() {
-        // should only be called on root
-        /* c8 ignore start */
-        if (this !== this.#root)
-            return this.#root.toMMPattern();
-        /* c8 ignore stop */
-        const glob = this.toString();
-        const [re, body, hasMagic, uflag] = this.toRegExpSource();
-        // if we're in nocase mode, and not nocaseMagicOnly, then we do
-        // still need a regular expression if we have to case-insensitively
-        // match capital/lowercase characters.
-        const anyMagic = hasMagic ||
-            this.#hasMagic ||
-            (this.#options.nocase &&
-                !this.#options.nocaseMagicOnly &&
-                glob.toUpperCase() !== glob.toLowerCase());
-        if (!anyMagic) {
-            return body;
-        }
-        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
-        return Object.assign(new RegExp(`^${re}$`, flags), {
-            _src: re,
-            _glob: glob,
-        });
-    }
-    get options() {
-        return this.#options;
-    }
-    // returns the string match, the regexp source, whether there's magic
-    // in the regexp (so a regular expression is required) and whether or
-    // not the uflag is needed for the regular expression (for posix classes)
-    // TODO: instead of injecting the start/end at this point, just return
-    // the BODY of the regexp, along with the start/end portions suitable
-    // for binding the start/end in either a joined full-path makeRe context
-    // (where we bind to (^|/), or a standalone matchPart context (where
-    // we bind to ^, and not /).  Otherwise slashes get duped!
-    //
-    // In part-matching mode, the start is:
-    // - if not isStart: nothing
-    // - if traversal possible, but not allowed: ^(?!\.\.?$)
-    // - if dots allowed or not possible: ^
-    // - if dots possible and not allowed: ^(?!\.)
-    // end is:
-    // - if not isEnd(): nothing
-    // - else: $
-    //
-    // In full-path matching mode, we put the slash at the START of the
-    // pattern, so start is:
-    // - if first pattern: same as part-matching mode
-    // - if not isStart(): nothing
-    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
-    // - if dots allowed or not possible: /
-    // - if dots possible and not allowed: /(?!\.)
-    // end is:
-    // - if last pattern, same as part-matching mode
-    // - else nothing
-    //
-    // Always put the (?:$|/) on negated tails, though, because that has to be
-    // there to bind the end of the negated pattern portion, and it's easier to
-    // just stick it in now rather than try to inject it later in the middle of
-    // the pattern.
-    //
-    // We can just always return the same end, and leave it up to the caller
-    // to know whether it's going to be used joined or in parts.
-    // And, if the start is adjusted slightly, can do the same there:
-    // - if not isStart: nothing
-    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
-    // - if dots allowed or not possible: (?:/|^)
-    // - if dots possible and not allowed: (?:/|^)(?!\.)
-    //
-    // But it's better to have a simpler binding without a conditional, for
-    // performance, so probably better to return both start options.
-    //
-    // Then the caller just ignores the end if it's not the first pattern,
-    // and the start always gets applied.
-    //
-    // But that's always going to be $ if it's the ending pattern, or nothing,
-    // so the caller can just attach $ at the end of the pattern when building.
-    //
-    // So the todo is:
-    // - better detect what kind of start is needed
-    // - return both flavors of starting pattern
-    // - attach $ at the end of the pattern when creating the actual RegExp
-    //
-    // Ah, but wait, no, that all only applies to the root when the first pattern
-    // is not an extglob. If the first pattern IS an extglob, then we need all
-    // that dot prevention biz to live in the extglob portions, because eg
-    // +(*|.x*) can match .xy but not .yx.
-    //
-    // So, return the two flavors if it's #root and the first child is not an
-    // AST, otherwise leave it to the child AST to handle it, and there,
-    // use the (?:^|/) style of start binding.
-    //
-    // Even simplified further:
-    // - Since the start for a join is eg /(?!\.) and the start for a part
-    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
-    // or start or whatever) and prepend ^ or / at the Regexp construction.
-    toRegExpSource(allowDot) {
-        const dot = allowDot ?? !!this.#options.dot;
-        if (this.#root === this) {
-            this.#flatten();
-            this.#fillNegs();
-        }
-        if (!isExtglobAST(this)) {
-            const noEmpty = this.isStart() &&
-                this.isEnd() &&
-                !this.#parts.some(s => typeof s !== 'string');
-            const src = this.#parts
-                .map(p => {
-                const [re, _, hasMagic, uflag] = typeof p === 'string' ?
-                    _a.#parseGlob(p, this.#hasMagic, noEmpty)
-                    : p.toRegExpSource(allowDot);
-                this.#hasMagic = this.#hasMagic || hasMagic;
-                this.#uflag = this.#uflag || uflag;
-                return re;
-            })
-                .join('');
-            let start = '';
-            if (this.isStart()) {
-                if (typeof this.#parts[0] === 'string') {
-                    // this is the string that will match the start of the pattern,
-                    // so we need to protect against dots and such.
-                    // '.' and '..' cannot match unless the pattern is that exactly,
-                    // even if it starts with . or dot:true is set.
-                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
-                    if (!dotTravAllowed) {
-                        const aps = addPatternStart;
-                        // check if we have a possibility of matching . or ..,
-                        // and prevent that.
-                        const needNoTrav = 
-                        // dots are allowed, and the pattern starts with [ or .
-                        (dot && aps.has(src.charAt(0))) ||
-                            // the pattern starts with \., and then [ or .
-                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
-                            // the pattern starts with \.\., and then [ or .
-                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
-                        // no need to prevent dots if it can't match a dot, or if a
-                        // sub-pattern will be preventing it anyway.
-                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
-                        start =
-                            needNoTrav ? startNoTraversal
-                                : needNoDot ? startNoDot
-                                    : '';
-                    }
-                }
-            }
-            // append the "end of path portion" pattern to negation tails
-            let end = '';
-            if (this.isEnd() &&
-                this.#root.#filledNegs &&
-                this.#parent?.type === '!') {
-                end = '(?:$|\\/)';
-            }
-            const final = start + src + end;
-            return [
-                final,
-                unescape(src),
-                (this.#hasMagic = !!this.#hasMagic),
-                this.#uflag,
-            ];
-        }
-        // We need to calculate the body *twice* if it's a repeat pattern
-        // at the start, once in nodot mode, then again in dot mode, so a
-        // pattern like *(?) can match 'x.y'
-        const repeated = this.type === '*' || this.type === '+';
-        // some kind of extglob
-        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
-        let body = this.#partsToRegExp(dot);
-        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
-            // invalid extglob, has to at least be *something* present, if it's
-            // the entire path portion.
-            const s = this.toString();
-            const me = this;
-            me.#parts = [s];
-            me.type = null;
-            me.#hasMagic = undefined;
-            return [s, unescape(this.toString()), false, false];
-        }
-        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
-            ''
-            : this.#partsToRegExp(true);
-        if (bodyDotAllowed === body) {
-            bodyDotAllowed = '';
-        }
-        if (bodyDotAllowed) {
-            body = `(?:${body})(?:${bodyDotAllowed})*?`;
-        }
-        // an empty !() is exactly equivalent to a starNoEmpty
-        let final = '';
-        if (this.type === '!' && this.#emptyExt) {
-            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
-        }
-        else {
-            const close = this.type === '!' ?
-                // !() must match something,but !(x) can match ''
-                '))' +
-                    (this.isStart() && !dot && !allowDot ? startNoDot : '') +
-                    star +
-                    ')'
-                : this.type === '@' ? ')'
-                    : this.type === '?' ? ')?'
-                        : this.type === '+' && bodyDotAllowed ? ')'
-                            : this.type === '*' && bodyDotAllowed ? `)?`
-                                : `)${this.type}`;
-            final = start + body + close;
-        }
-        return [
-            final,
-            unescape(body),
-            (this.#hasMagic = !!this.#hasMagic),
-            this.#uflag,
-        ];
-    }
-    #flatten() {
-        if (!isExtglobAST(this)) {
-            for (const p of this.#parts) {
-                if (typeof p === 'object') {
-                    p.#flatten();
-                }
-            }
-        }
-        else {
-            // do up to 10 passes to flatten as much as possible
-            let iterations = 0;
-            let done = false;
-            do {
-                done = true;
-                for (let i = 0; i < this.#parts.length; i++) {
-                    const c = this.#parts[i];
-                    if (typeof c === 'object') {
-                        c.#flatten();
-                        if (this.#canAdopt(c)) {
-                            done = false;
-                            this.#adopt(c, i);
-                        }
-                        else if (this.#canAdoptWithSpace(c)) {
-                            done = false;
-                            this.#adoptWithSpace(c, i);
-                        }
-                        else if (this.#canUsurp(c)) {
-                            done = false;
-                            this.#usurp(c);
-                        }
-                    }
-                }
-            } while (!done && ++iterations < 10);
-        }
-        this.#toString = undefined;
-    }
-    #partsToRegExp(dot) {
-        return this.#parts
-            .map(p => {
-            // extglob ASTs should only contain parent ASTs
-            /* c8 ignore start */
-            if (typeof p === 'string') {
-                throw new Error('string type in extglob ast??');
-            }
-            /* c8 ignore stop */
-            // can ignore hasMagic, because extglobs are already always magic
-            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
-            this.#uflag = this.#uflag || uflag;
-            return re;
-        })
-            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
-            .join('|');
-    }
-    static #parseGlob(glob, hasMagic, noEmpty = false) {
-        let escaping = false;
-        let re = '';
-        let uflag = false;
-        // multiple stars that aren't globstars coalesce into one *
-        let inStar = false;
-        for (let i = 0; i < glob.length; i++) {
-            const c = glob.charAt(i);
-            if (escaping) {
-                escaping = false;
-                re += (reSpecials.has(c) ? '\\' : '') + c;
-                continue;
-            }
-            if (c === '*') {
-                if (inStar)
-                    continue;
-                inStar = true;
-                re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;
-                hasMagic = true;
-                continue;
-            }
-            else {
-                inStar = false;
-            }
-            if (c === '\\') {
-                if (i === glob.length - 1) {
-                    re += '\\\\';
-                }
-                else {
-                    escaping = true;
-                }
-                continue;
-            }
-            if (c === '[') {
-                const [src, needUflag, consumed, magic] = parseClass(glob, i);
-                if (consumed) {
-                    re += src;
-                    uflag = uflag || needUflag;
-                    i += consumed - 1;
-                    hasMagic = hasMagic || magic;
-                    continue;
-                }
-            }
-            if (c === '?') {
-                re += qmark;
-                hasMagic = true;
-                continue;
-            }
-            re += regExpEscape(c);
-        }
-        return [re, unescape(glob), !!hasMagic, uflag];
-    }
-}
-_a = AST;
-//# sourceMappingURL=ast.js.map
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.js.map
deleted file mode 100644
index f5cc3ee91a072b55b9ff2df2066afd50cf38a6ce..0000000000000000000000000000000000000000
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/ast.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"ast.js","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAAA,8BAA8B;;AAE9B,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAEnD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAwCxC,MAAM,KAAK,GAAG,IAAI,GAAG,C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CAAC,CAAC,CAAC,CAAA;QACvB,CAAC;QACD,OAAO,CAAC,EAAE,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;IAChD,CAAC;CACF","sourcesContent":["// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport type { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n//   1   2 3   4 5 6      1   2    3   46      5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n//                                 v----- .* because there's more following,\n//                                 v    v  otherwise, .+ because it must be\n//                                 v    v  *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n//   copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string | null): c is ExtglobType =>\n  types.has(c as ExtglobType)\nconst isExtglobAST = (c: AST): c is AST & { type: ExtglobType } =>\n  isExtglobType(c.type)\n\n// Map of which extglob types can adopt the children of a nested extglob\n//\n// anything but ! can adopt a matching type:\n// +(a|+(b|c)|d) => +(a|b|c|d)\n// *(a|*(b|c)|d) => *(a|b|c|d)\n// @(a|@(b|c)|d) => @(a|b|c|d)\n// ?(a|?(b|c)|d) => ?(a|b|c|d)\n//\n// * can adopt anything, because 0 or repetition is allowed\n// *(a|?(b|c)|d) => *(a|b|c|d)\n// *(a|+(b|c)|d) => *(a|b|c|d)\n// *(a|@(b|c)|d) => *(a|b|c|d)\n//\n// + can adopt @, because 1 or repetition is allowed\n// +(a|@(b|c)|d) => +(a|b|c|d)\n//\n// + and @ CANNOT adopt *, because 0 would be allowed\n// +(a|*(b|c)|d) => would match \"\", on *(b|c)\n// @(a|*(b|c)|d) => would match \"\", on *(b|c)\n//\n// + and @ CANNOT adopt ?, because 0 would be allowed\n// +(a|?(b|c)|d) => would match \"\", on ?(b|c)\n// @(a|?(b|c)|d) => would match \"\", on ?(b|c)\n//\n// ? can adopt @, because 0 or 1 is allowed\n// ?(a|@(b|c)|d) => ?(a|b|c|d)\n//\n// ? and @ CANNOT adopt * or +, because >1 would be allowed\n// ?(a|*(b|c)|d) => would match bbb on *(b|c)\n// @(a|*(b|c)|d) => would match bbb on *(b|c)\n// ?(a|+(b|c)|d) => would match bbb on +(b|c)\n// @(a|+(b|c)|d) => would match bbb on +(b|c)\n//\n// ! CANNOT adopt ! (nothing else can either)\n// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)\n//\n// ! can adopt @\n// !(a|@(b|c)|d) => !(a|b|c|d)\n//\n// ! CANNOT adopt *\n// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed\n//\n// ! CANNOT adopt +\n// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed\n//\n// ! CANNOT adopt ?\n// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match \"x\"\nconst adoptionMap = new Map([\n  ['!', ['@']],\n  ['?', ['?', '@']],\n  ['@', ['@']],\n  ['*', ['*', '+', '?', '@']],\n  ['+', ['+', '@']],\n])\n\n// nested extglobs that can be adopted in, but with the addition of\n// a blank '' element.\nconst adoptionWithSpaceMap = new Map([\n  ['!', ['?']],\n  ['@', ['?']],\n  ['+', ['?', '*']],\n])\n\n// union of the previous two maps\nconst adoptionAnyMap = new Map([\n  ['!', ['?', '@']],\n  ['?', ['?', '@']],\n  ['@', ['?', '@']],\n  ['*', ['*', '+', '?', '@']],\n  ['+', ['+', '@', '?', '*']],\n])\n\n// Extglobs that can take over their parent if they are the only child\n// the key is parent, value maps child to resulting extglob parent type\n// '@' is omitted because it's a special case. An `@` extglob with a single\n// member can always be usurped by that subpattern.\nconst usurpMap = new Map<\n  ExtglobType,\n  Map\n>([\n  ['!', new Map([['!', '@']])],\n  [\n    '?',\n    new Map([\n      ['*', '*'],\n      ['+', '*'],\n    ]),\n  ],\n  [\n    '@',\n    new Map([\n      ['!', '!'],\n      ['?', '?'],\n      ['@', '@'],\n      ['*', '*'],\n      ['+', '+'],\n    ]),\n  ],\n  [\n    '+',\n    new Map([\n      ['?', '*'],\n      ['*', '*'],\n    ]),\n  ],\n])\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nlet ID = 0\nexport class AST {\n  type: ExtglobType | null\n  readonly #root: AST\n\n  #hasMagic?: boolean\n  #uflag: boolean = false\n  #parts: (string | AST)[] = []\n  #parent?: AST\n  #parentIndex: number\n  #negs: AST[]\n  #filledNegs: boolean = false\n  #options: MinimatchOptions\n  #toString?: string\n  // set to true if it's an extglob with no children\n  // (which really means one child of '')\n  #emptyExt: boolean = false\n  id = ++ID\n\n  get depth(): number {\n    return (this.#parent?.depth ?? -1) + 1\n  }\n\n  [Symbol.for('nodejs.util.inspect.custom')]() {\n    return {\n      '@@type': 'AST',\n      id: this.id,\n      type: this.type,\n      root: this.#root.id,\n      parent: this.#parent?.id,\n      depth: this.depth,\n      partsLength: this.#parts.length,\n      parts: this.#parts,\n    }\n  }\n\n  constructor(\n    type: ExtglobType | null,\n    parent?: AST,\n    options: MinimatchOptions = {},\n  ) {\n    this.type = type\n    // extglobs are inherently magical\n    if (type) this.#hasMagic = true\n    this.#parent = parent\n    this.#root = this.#parent ? this.#parent.#root : this\n    this.#options = this.#root === this ? options : this.#root.#options\n    this.#negs = this.#root === this ? [] : this.#root.#negs\n    if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n    this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n  }\n\n  get hasMagic(): boolean | undefined {\n    /* c8 ignore start */\n    if (this.#hasMagic !== undefined) return this.#hasMagic\n    /* c8 ignore stop */\n    for (const p of this.#parts) {\n      if (typeof p === 'string') continue\n      if (p.type || p.hasMagic) return (this.#hasMagic = true)\n    }\n    // note: will be undefined until we generate the regexp src and find out\n    return this.#hasMagic\n  }\n\n  // reconstructs the pattern\n  toString(): string {\n    return (\n      this.#toString !== undefined ? this.#toString\n      : !this.type ?\n        (this.#toString = this.#parts.map(p => String(p)).join(''))\n      : (this.#toString =\n          this.type +\n          '(' +\n          this.#parts.map(p => String(p)).join('|') +\n          ')')\n    )\n  }\n\n  #fillNegs() {\n    /* c8 ignore start */\n    if (this !== this.#root) throw new Error('should only call on root')\n    if (this.#filledNegs) return this\n    /* c8 ignore stop */\n\n    // call toString() once to fill this out\n    this.toString()\n    this.#filledNegs = true\n    let n: AST | undefined\n    while ((n = this.#negs.pop())) {\n      if (n.type !== '!') continue\n      // walk up the tree, appending everthing that comes AFTER parentIndex\n      let p: AST | undefined = n\n      let pp = p.#parent\n      while (pp) {\n        for (\n          let i = p.#parentIndex + 1;\n          !pp.type && i < pp.#parts.length;\n          i++\n        ) {\n          for (const part of n.#parts) {\n            /* c8 ignore start */\n            if (typeof part === 'string') {\n              throw new Error('string part in extglob AST??')\n            }\n            /* c8 ignore stop */\n            part.copyIn(pp.#parts[i])\n          }\n        }\n        p = pp\n        pp = p.#parent\n      }\n    }\n    return this\n  }\n\n  push(...parts: (string | AST)[]) {\n    for (const p of parts) {\n      if (p === '') continue\n      /* c8 ignore start */\n      if (\n        typeof p !== 'string' &&\n        !(p instanceof AST && p.#parent === this)\n      ) {\n        throw new Error('invalid part: ' + p)\n      }\n      /* c8 ignore stop */\n      this.#parts.push(p)\n    }\n  }\n\n  toJSON() {\n    const ret: unknown[] =\n      this.type === null ?\n        this.#parts\n          .slice()\n          .map(p => (typeof p === 'string' ? p : p.toJSON()))\n      : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n    if (this.isStart() && !this.type) ret.unshift([])\n    if (\n      this.isEnd() &&\n      (this === this.#root ||\n        (this.#root.#filledNegs && this.#parent?.type === '!'))\n    ) {\n      ret.push({})\n    }\n    return ret\n  }\n\n  isStart(): boolean {\n    if (this.#root === this) return true\n    // if (this.type) return !!this.#parent?.isStart()\n    if (!this.#parent?.isStart()) return false\n    if (this.#parentIndex === 0) return true\n    // if everything AHEAD of this is a negation, then it's still the \"start\"\n    const p = this.#parent\n    for (let i = 0; i < this.#parentIndex; i++) {\n      const pp = p.#parts[i]\n      if (!(pp instanceof AST && pp.type === '!')) {\n        return false\n      }\n    }\n    return true\n  }\n\n  isEnd(): boolean {\n    if (this.#root === this) return true\n    if (this.#parent?.type === '!') return true\n    if (!this.#parent?.isEnd()) return false\n    if (!this.type) return this.#parent?.isEnd()\n    // if not root, it'll always have a parent\n    /* c8 ignore start */\n    const pl = this.#parent ? this.#parent.#parts.length : 0\n    /* c8 ignore stop */\n    return this.#parentIndex === pl - 1\n  }\n\n  copyIn(part: AST | string) {\n    if (typeof part === 'string') this.push(part)\n    else this.push(part.clone(this))\n  }\n\n  clone(parent: AST) {\n    const c = new AST(this.type, parent)\n    for (const p of this.#parts) {\n      c.copyIn(p)\n    }\n    return c\n  }\n\n  static #parseAST(\n    str: string,\n    ast: AST,\n    pos: number,\n    opt: MinimatchOptions,\n    extDepth: number,\n  ): number {\n    const maxDepth = opt.maxExtglobRecursion ?? 2\n    let escaping = false\n    let inBrace = false\n    let braceStart = -1\n    let braceNeg = false\n    if (ast.type === null) {\n      // outside of a extglob, append until we find a start\n      let i = pos\n      let acc = ''\n      while (i < str.length) {\n        const c = str.charAt(i++)\n        // still accumulate escapes at this point, but we do ignore\n        // starts that are escaped\n        if (escaping || c === '\\\\') {\n          escaping = !escaping\n          acc += c\n          continue\n        }\n\n        if (inBrace) {\n          if (i === braceStart + 1) {\n            if (c === '^' || c === '!') {\n              braceNeg = true\n            }\n          } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n            inBrace = false\n          }\n          acc += c\n          continue\n        } else if (c === '[') {\n          inBrace = true\n          braceStart = i\n          braceNeg = false\n          acc += c\n          continue\n        }\n\n        // we don't have to check for adoption here, because that's\n        // done at the other recursion point.\n        const doRecurse =\n          !opt.noext &&\n          isExtglobType(c) &&\n          str.charAt(i) === '(' &&\n          extDepth <= maxDepth\n        if (doRecurse) {\n          ast.push(acc)\n          acc = ''\n          const ext = new AST(c, ast)\n          i = AST.#parseAST(str, ext, i, opt, extDepth + 1)\n          ast.push(ext)\n          continue\n        }\n        acc += c\n      }\n      ast.push(acc)\n      return i\n    }\n\n    // some kind of extglob, pos is at the (\n    // find the next | or )\n    let i = pos + 1\n    let part = new AST(null, ast)\n    const parts: AST[] = []\n    let acc = ''\n    while (i < str.length) {\n      const c = str.charAt(i++)\n      // still accumulate escapes at this point, but we do ignore\n      // starts that are escaped\n      if (escaping || c === '\\\\') {\n        escaping = !escaping\n        acc += c\n        continue\n      }\n\n      if (inBrace) {\n        if (i === braceStart + 1) {\n          if (c === '^' || c === '!') {\n            braceNeg = true\n          }\n        } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n          inBrace = false\n        }\n        acc += c\n        continue\n      } else if (c === '[') {\n        inBrace = true\n        braceStart = i\n        braceNeg = false\n        acc += c\n        continue\n      }\n\n      const doRecurse =\n        !opt.noext &&\n        isExtglobType(c) &&\n        str.charAt(i) === '(' &&\n        /* c8 ignore start - the maxDepth is sufficient here */\n        (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)))\n      /* c8 ignore stop */\n      if (doRecurse) {\n        const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1\n        part.push(acc)\n        acc = ''\n        const ext = new AST(c, part)\n        part.push(ext)\n        i = AST.#parseAST(str, ext, i, opt, extDepth + depthAdd)\n        continue\n      }\n      if (c === '|') {\n        part.push(acc)\n        acc = ''\n        parts.push(part)\n        part = new AST(null, ast)\n        continue\n      }\n      if (c === ')') {\n        if (acc === '' && ast.#parts.length === 0) {\n          ast.#emptyExt = true\n        }\n        part.push(acc)\n        acc = ''\n        ast.push(...parts, part)\n        return i\n      }\n      acc += c\n    }\n\n    // unfinished extglob\n    // if we got here, it was a malformed extglob! not an extglob, but\n    // maybe something else in there.\n    ast.type = null\n    ast.#hasMagic = undefined\n    ast.#parts = [str.substring(pos - 1)]\n    return i\n  }\n\n  #canAdoptWithSpace(child?: AST | string): child is AST & {\n    type: null\n    parts: [AST & { type: ExtglobType }]\n  } {\n    return this.#canAdopt(child, adoptionWithSpaceMap)\n  }\n\n  #canAdopt(\n    child?: AST | string,\n    map: Map = adoptionMap,\n  ): child is AST & {\n    type: null\n    parts: [AST & { type: ExtglobType }]\n  } {\n    if (\n      !child ||\n      typeof child !== 'object' ||\n      child.type !== null ||\n      child.#parts.length !== 1 ||\n      this.type === null\n    ) {\n      return false\n    }\n    const gc = child.#parts[0]\n    if (!gc || typeof gc !== 'object' || gc.type === null) {\n      return false\n    }\n    return (this as AST & { type: ExtglobType }).#canAdoptType(\n      gc.type,\n      map,\n    )\n  }\n  #canAdoptType(\n    c: string,\n    map: Map = adoptionAnyMap,\n  ): c is ExtglobType {\n    return !!map.get(this.type as ExtglobType)?.includes(c as ExtglobType)\n  }\n\n  #adoptWithSpace(\n    this: AST & { type: ExtglobType },\n    child: AST & {\n      type: null\n    },\n    index: number,\n  ) {\n    const gc = child.#parts[0] as AST & { type: ExtglobType }\n    const blank = new AST(null, gc, this.options)\n    blank.#parts.push('')\n    gc.push(blank)\n    this.#adopt(child, index)\n  }\n\n  #adopt(\n    child: AST & {\n      type: null\n    },\n    index: number,\n  ) {\n    const gc = child.#parts[0] as AST & { type: ExtglobType }\n    this.#parts.splice(index, 1, ...gc.#parts)\n    for (const p of gc.#parts) {\n      if (typeof p === 'object') p.#parent = this\n    }\n    this.#toString = undefined\n  }\n\n  #canUsurpType(c: string): boolean {\n    const m = usurpMap.get(this.type as ExtglobType)\n    return !!m?.has(c as ExtglobType)\n  }\n\n  #canUsurp(child?: AST | string): child is AST & {\n    type: null\n    parts: [AST & { type: ExtglobType }]\n  } {\n    if (\n      !child ||\n      typeof child !== 'object' ||\n      child.type !== null ||\n      child.#parts.length !== 1 ||\n      this.type === null ||\n      this.#parts.length !== 1\n    ) {\n      return false\n    }\n    const gc = child.#parts[0]\n    if (!gc || typeof gc !== 'object' || gc.type === null) {\n      return false\n    }\n    return (this as AST & { type: ExtglobType }).#canUsurpType(gc.type)\n  }\n\n  #usurp(this: AST & { type: ExtglobType }, child: AST & { type: null }) {\n    const m = usurpMap.get(this.type as ExtglobType)\n    const gc = child.#parts[0] as AST & { type: ExtglobType }\n    const nt = m?.get(gc.type)\n    /* c8 ignore start - impossible */\n    if (!nt) return false\n    /* c8 ignore stop */\n    this.#parts = gc.#parts\n    for (const p of this.#parts) {\n      if (typeof p === 'object') {\n        p.#parent = this\n      }\n    }\n    this.type = nt\n    this.#toString = undefined\n    this.#emptyExt = false\n  }\n\n  static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n    const ast = new AST(null, undefined, options)\n    AST.#parseAST(pattern, ast, 0, options, 0)\n    return ast\n  }\n\n  // returns the regular expression if there's magic, or the unescaped\n  // string if not.\n  toMMPattern(): MMRegExp | string {\n    // should only be called on root\n    /* c8 ignore start */\n    if (this !== this.#root) return this.#root.toMMPattern()\n    /* c8 ignore stop */\n    const glob = this.toString()\n    const [re, body, hasMagic, uflag] = this.toRegExpSource()\n    // if we're in nocase mode, and not nocaseMagicOnly, then we do\n    // still need a regular expression if we have to case-insensitively\n    // match capital/lowercase characters.\n    const anyMagic =\n      hasMagic ||\n      this.#hasMagic ||\n      (this.#options.nocase &&\n        !this.#options.nocaseMagicOnly &&\n        glob.toUpperCase() !== glob.toLowerCase())\n    if (!anyMagic) {\n      return body\n    }\n\n    const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n    return Object.assign(new RegExp(`^${re}$`, flags), {\n      _src: re,\n      _glob: glob,\n    })\n  }\n\n  get options() {\n    return this.#options\n  }\n\n  // returns the string match, the regexp source, whether there's magic\n  // in the regexp (so a regular expression is required) and whether or\n  // not the uflag is needed for the regular expression (for posix classes)\n  // TODO: instead of injecting the start/end at this point, just return\n  // the BODY of the regexp, along with the start/end portions suitable\n  // for binding the start/end in either a joined full-path makeRe context\n  // (where we bind to (^|/), or a standalone matchPart context (where\n  // we bind to ^, and not /).  Otherwise slashes get duped!\n  //\n  // In part-matching mode, the start is:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n  // - if dots allowed or not possible: ^\n  // - if dots possible and not allowed: ^(?!\\.)\n  // end is:\n  // - if not isEnd(): nothing\n  // - else: $\n  //\n  // In full-path matching mode, we put the slash at the START of the\n  // pattern, so start is:\n  // - if first pattern: same as part-matching mode\n  // - if not isStart(): nothing\n  // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n  // - if dots allowed or not possible: /\n  // - if dots possible and not allowed: /(?!\\.)\n  // end is:\n  // - if last pattern, same as part-matching mode\n  // - else nothing\n  //\n  // Always put the (?:$|/) on negated tails, though, because that has to be\n  // there to bind the end of the negated pattern portion, and it's easier to\n  // just stick it in now rather than try to inject it later in the middle of\n  // the pattern.\n  //\n  // We can just always return the same end, and leave it up to the caller\n  // to know whether it's going to be used joined or in parts.\n  // And, if the start is adjusted slightly, can do the same there:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n  // - if dots allowed or not possible: (?:/|^)\n  // - if dots possible and not allowed: (?:/|^)(?!\\.)\n  //\n  // But it's better to have a simpler binding without a conditional, for\n  // performance, so probably better to return both start options.\n  //\n  // Then the caller just ignores the end if it's not the first pattern,\n  // and the start always gets applied.\n  //\n  // But that's always going to be $ if it's the ending pattern, or nothing,\n  // so the caller can just attach $ at the end of the pattern when building.\n  //\n  // So the todo is:\n  // - better detect what kind of start is needed\n  // - return both flavors of starting pattern\n  // - attach $ at the end of the pattern when creating the actual RegExp\n  //\n  // Ah, but wait, no, that all only applies to the root when the first pattern\n  // is not an extglob. If the first pattern IS an extglob, then we need all\n  // that dot prevention biz to live in the extglob portions, because eg\n  // +(*|.x*) can match .xy but not .yx.\n  //\n  // So, return the two flavors if it's #root and the first child is not an\n  // AST, otherwise leave it to the child AST to handle it, and there,\n  // use the (?:^|/) style of start binding.\n  //\n  // Even simplified further:\n  // - Since the start for a join is eg /(?!\\.) and the start for a part\n  // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n  // or start or whatever) and prepend ^ or / at the Regexp construction.\n  toRegExpSource(\n    allowDot?: boolean,\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    const dot = allowDot ?? !!this.#options.dot\n    if (this.#root === this) {\n      this.#flatten()\n      this.#fillNegs()\n    }\n    if (!isExtglobAST(this)) {\n      const noEmpty =\n        this.isStart() &&\n        this.isEnd() &&\n        !this.#parts.some(s => typeof s !== 'string')\n      const src = this.#parts\n        .map(p => {\n          const [re, _, hasMagic, uflag] =\n            typeof p === 'string' ?\n              AST.#parseGlob(p, this.#hasMagic, noEmpty)\n            : p.toRegExpSource(allowDot)\n          this.#hasMagic = this.#hasMagic || hasMagic\n          this.#uflag = this.#uflag || uflag\n          return re\n        })\n        .join('')\n\n      let start = ''\n      if (this.isStart()) {\n        if (typeof this.#parts[0] === 'string') {\n          // this is the string that will match the start of the pattern,\n          // so we need to protect against dots and such.\n\n          // '.' and '..' cannot match unless the pattern is that exactly,\n          // even if it starts with . or dot:true is set.\n          const dotTravAllowed =\n            this.#parts.length === 1 && justDots.has(this.#parts[0])\n          if (!dotTravAllowed) {\n            const aps = addPatternStart\n            // check if we have a possibility of matching . or ..,\n            // and prevent that.\n            const needNoTrav =\n              // dots are allowed, and the pattern starts with [ or .\n              (dot && aps.has(src.charAt(0))) ||\n              // the pattern starts with \\., and then [ or .\n              (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n              // the pattern starts with \\.\\., and then [ or .\n              (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n            // no need to prevent dots if it can't match a dot, or if a\n            // sub-pattern will be preventing it anyway.\n            const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n            start =\n              needNoTrav ? startNoTraversal\n              : needNoDot ? startNoDot\n              : ''\n          }\n        }\n      }\n\n      // append the \"end of path portion\" pattern to negation tails\n      let end = ''\n      if (\n        this.isEnd() &&\n        this.#root.#filledNegs &&\n        this.#parent?.type === '!'\n      ) {\n        end = '(?:$|\\\\/)'\n      }\n      const final = start + src + end\n      return [\n        final,\n        unescape(src),\n        (this.#hasMagic = !!this.#hasMagic),\n        this.#uflag,\n      ]\n    }\n\n    // We need to calculate the body *twice* if it's a repeat pattern\n    // at the start, once in nodot mode, then again in dot mode, so a\n    // pattern like *(?) can match 'x.y'\n\n    const repeated = this.type === '*' || this.type === '+'\n    // some kind of extglob\n    const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n    let body = (this as AST & { type: ExtglobType }).#partsToRegExp(dot)\n\n    if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n      // invalid extglob, has to at least be *something* present, if it's\n      // the entire path portion.\n      const s = this.toString()\n      const me = this as AST\n      me.#parts = [s]\n      me.type = null\n      me.#hasMagic = undefined\n      return [s, unescape(this.toString()), false, false]\n    }\n\n    let bodyDotAllowed =\n      !repeated || allowDot || dot || !startNoDot ?\n        ''\n      : this.#partsToRegExp(true)\n    if (bodyDotAllowed === body) {\n      bodyDotAllowed = ''\n    }\n    if (bodyDotAllowed) {\n      body = `(?:${body})(?:${bodyDotAllowed})*?`\n    }\n\n    // an empty !() is exactly equivalent to a starNoEmpty\n    let final = ''\n    if (this.type === '!' && this.#emptyExt) {\n      final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n    } else {\n      const close =\n        this.type === '!' ?\n          // !() must match something,but !(x) can match ''\n          '))' +\n          (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n          star +\n          ')'\n        : this.type === '@' ? ')'\n        : this.type === '?' ? ')?'\n        : this.type === '+' && bodyDotAllowed ? ')'\n        : this.type === '*' && bodyDotAllowed ? `)?`\n        : `)${this.type}`\n      final = start + body + close\n    }\n    return [\n      final,\n      unescape(body),\n      (this.#hasMagic = !!this.#hasMagic),\n      this.#uflag,\n    ]\n  }\n\n  #flatten() {\n    if (!isExtglobAST(this)) {\n      for (const p of this.#parts) {\n        if (typeof p === 'object') {\n          p.#flatten()\n        }\n      }\n    } else {\n      // do up to 10 passes to flatten as much as possible\n      let iterations = 0\n      let done = false\n      do {\n        done = true\n        for (let i = 0; i < this.#parts.length; i++) {\n          const c = this.#parts[i]\n          if (typeof c === 'object') {\n            c.#flatten()\n            if (this.#canAdopt(c)) {\n              done = false\n              this.#adopt(c, i)\n            } else if (this.#canAdoptWithSpace(c)) {\n              done = false\n              ;(this as AST & { type: ExtglobType }).#adoptWithSpace(c, i)\n            } else if (this.#canUsurp(c)) {\n              done = false\n              ;(this as AST & { type: ExtglobType }).#usurp(c)\n            }\n          }\n        }\n      } while (!done && ++iterations < 10)\n    }\n    this.#toString = undefined\n  }\n\n  #partsToRegExp(this: AST & { type: ExtglobType }, dot: boolean) {\n    return this.#parts\n      .map(p => {\n        // extglob ASTs should only contain parent ASTs\n        /* c8 ignore start */\n        if (typeof p === 'string') {\n          throw new Error('string type in extglob ast??')\n        }\n        /* c8 ignore stop */\n        // can ignore hasMagic, because extglobs are already always magic\n        const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n        this.#uflag = this.#uflag || uflag\n        return re\n      })\n      .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n      .join('|')\n  }\n\n  static #parseGlob(\n    glob: string,\n    hasMagic: boolean | undefined,\n    noEmpty: boolean = false,\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    let escaping = false\n    let re = ''\n    let uflag = false\n    // multiple stars that aren't globstars coalesce into one *\n    let inStar = false\n    for (let i = 0; i < glob.length; i++) {\n      const c = glob.charAt(i)\n      if (escaping) {\n        escaping = false\n        re += (reSpecials.has(c) ? '\\\\' : '') + c\n        continue\n      }\n      if (c === '*') {\n        if (inStar) continue\n        inStar = true\n        re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star\n        hasMagic = true\n        continue\n      } else {\n        inStar = false\n      }\n      if (c === '\\\\') {\n        if (i === glob.length - 1) {\n          re += '\\\\\\\\'\n        } else {\n          escaping = true\n        }\n        continue\n      }\n      if (c === '[') {\n        const [src, needUflag, consumed, magic] = parseClass(glob, i)\n        if (consumed) {\n          re += src\n          uflag = uflag || needUflag\n          i += consumed - 1\n          hasMagic = hasMagic || magic\n          continue\n        }\n      }\n      if (c === '?') {\n        re += qmark\n        hasMagic = true\n        continue\n      }\n      re += regExpEscape(c)\n    }\n    return [re, unescape(glob), !!hasMagic, uflag]\n  }\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.d.ts b/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.d.ts
deleted file mode 100644
index b1572deb95e2e376474f9fc1e56e4c38a055fbd1..0000000000000000000000000000000000000000
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.d.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export type ParseClassResult = [
-    src: string,
-    uFlag: boolean,
-    consumed: number,
-    hasMagic: boolean
-];
-export declare const parseClass: (glob: string, position: number) => ParseClassResult;
-//# sourceMappingURL=brace-expressions.d.ts.map
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map
deleted file mode 100644
index 09b4c11060de7850a23ad17948c7d5d674850576..0000000000000000000000000000000000000000
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AAgCA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,KACf,gBA2HF,CAAA"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.js.map
deleted file mode 100644
index 184b5a89c11f4cc9705018a2b11a36cd7acacf02..0000000000000000000000000000000000000000
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/brace-expressions.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"brace-expressions.js","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,wCAAwC;AAExC,8DAA8D;AAC9D,MAAM,YAAY,GAChB;IACE,WAAW,EAAE,CAAC,sBAAsB,EAAE,IAAI,CAAC;IAC3C,WAAW,EAAE,CAAC,eAAe,EAAE,IAAI,CAAC;IACpC,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC;IAC7C,WAAW,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC;IACjC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,EAAE,IAAI,CAAC;IACzC,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,uBAAuB,EAAE,IAAI,CAAC;IAC5C,WAAW,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC;IAC9B,UAAU,EAAE,CAAC,6BAA6B,EAAE,IAAI,CAAC;IACjD,YAAY,EAAE,CAAC,WAAW,EAAE,KAAK,CAAC;CACnC,CAAA;AAEH,+DAA+D;AAC/D,mBAAmB;AACnB,MAAM,WAAW,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,O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n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } =\n  {\n    '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n    '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n    '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n    '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n    '[:cntrl:]': ['\\\\p{Cc}', true],\n    '[:digit:]': ['\\\\p{Nd}', true],\n    '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n    '[:lower:]': ['\\\\p{Ll}', true],\n    '[:print:]': ['\\\\p{C}', true],\n    '[:punct:]': ['\\\\p{P}', true],\n    '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n    '[:upper:]': ['\\\\p{Lu}', true],\n    '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n    '[:xdigit:]': ['A-Fa-f0-9', false],\n  }\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n  src: string,\n  uFlag: boolean,\n  consumed: number,\n  hasMagic: boolean,\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n  glob: string,\n  position: number,\n): ParseClassResult => {\n  const pos = position\n  /* c8 ignore start */\n  if (glob.charAt(pos) !== '[') {\n    throw new Error('not in a brace expression')\n  }\n  /* c8 ignore stop */\n  const ranges: string[] = []\n  const negs: string[] = []\n\n  let i = pos + 1\n  let sawStart = false\n  let uflag = false\n  let escaping = false\n  let negate = false\n  let endPos = pos\n  let rangeStart = ''\n  WHILE: while (i < glob.length) {\n    const c = glob.charAt(i)\n    if ((c === '!' || c === '^') && i === pos + 1) {\n      negate = true\n      i++\n      continue\n    }\n\n    if (c === ']' && sawStart && !escaping) {\n      endPos = i + 1\n      break\n    }\n\n    sawStart = true\n    if (c === '\\\\') {\n      if (!escaping) {\n        escaping = true\n        i++\n        continue\n      }\n      // escaped \\ char, fall through and treat like normal char\n    }\n    if (c === '[' && !escaping) {\n      // either a posix class, a collation equivalent, or just a [\n      for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n        if (glob.startsWith(cls, i)) {\n          // invalid, [a-[] is fine, but not [a-[:alpha]]\n          if (rangeStart) {\n            return ['$.', false, glob.length - pos, true]\n          }\n          i += cls.length\n          if (neg) negs.push(unip)\n          else ranges.push(unip)\n          uflag = uflag || u\n          continue WHILE\n        }\n      }\n    }\n\n    // now it's just a normal character, effectively\n    escaping = false\n    if (rangeStart) {\n      // throw this range away if it's not valid, but others\n      // can still match.\n      if (c > rangeStart) {\n        ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n      } else if (c === rangeStart) {\n        ranges.push(braceEscape(c))\n      }\n      rangeStart = ''\n      i++\n      continue\n    }\n\n    // now might be the start of a range.\n    // can be either c-d or c-] or c] or c] at this point\n    if (glob.startsWith('-]', i + 1)) {\n      ranges.push(braceEscape(c + '-'))\n      i += 2\n      continue\n    }\n    if (glob.startsWith('-', i + 1)) {\n      rangeStart = c\n      i += 2\n      continue\n    }\n\n    // not the start of a range, just a single character\n    ranges.push(braceEscape(c))\n    i++\n  }\n\n  if (endPos < i) {\n    // didn't see the end of the class, not a valid class,\n    // but might still be valid as a literal match.\n    return ['', false, 0, false]\n  }\n\n  // if we got no ranges and no negates, then we have a range that\n  // cannot possibly match anything, and that poisons the whole glob\n  if (!ranges.length && !negs.length) {\n    return ['$.', false, glob.length - pos, true]\n  }\n\n  // if we got one positive range, and it's a single character, then that's\n  // not actually a magic pattern, it's just that one literal character.\n  // we should not treat that as \"magic\", we should just return the literal\n  // character. [_] is a perfectly valid way to escape glob magic chars.\n  if (\n    negs.length === 0 &&\n    ranges.length === 1 &&\n    /^\\\\?.$/.test(ranges[0]) &&\n    !negate\n  ) {\n    const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n    return [regexpEscape(r), false, endPos - pos, false]\n  }\n\n  const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n  const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n  const comb =\n    ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n    : ranges.length ? sranges\n    : snegs\n\n  return [comb, uflag, endPos - pos, true]\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.d.ts b/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.d.ts
index 141024a06bdf747fe6d6ecc48a80675dff795800..202b981612906fd1b56445fb2fcb2aae54fd9103 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.d.ts
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.d.ts
@@ -10,6 +10,10 @@ import type { MinimatchOptions } from './index.js';
  *
  * If the {@link MinimatchOptions.magicalBraces} option is used,
  * then braces (`{` and `}`) will be escaped.
+ *
+ * A leading `#` or `!` is escaped as well, so that the result is never a
+ * comment or a negated pattern. In `windowsPathsNoEscape` mode, a leading
+ * `!` is written as `@(!)`, because `[!` starts a negated class.
  */
 export declare const escape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick) => string;
 //# sourceMappingURL=escape.d.ts.map
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.d.ts.map
index e167e30065a04e54a37b3f6e6b44275c42c3c602..ad38ae9f582b9c6a20d9e02df2b4dfec0b729429 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.d.ts.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,MAAM,GACjB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAazE,CAAA"}
\ No newline at end of file
+{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,MAAM,GACjB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAyBzE,CAAA"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.js b/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.js
index 46d0ec8858e5b3a2fdc692dfb6fbe69fb37c4068..933348679c1ca2b96c47d8b71e2296db521ba623 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.js
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.js
@@ -9,18 +9,33 @@
  *
  * If the {@link MinimatchOptions.magicalBraces} option is used,
  * then braces (`{` and `}`) will be escaped.
+ *
+ * A leading `#` or `!` is escaped as well, so that the result is never a
+ * comment or a negated pattern. In `windowsPathsNoEscape` mode, a leading
+ * `!` is written as `@(!)`, because `[!` starts a negated class.
  */
 export const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
     // don't need to escape +@! because we escape the parens
     // that make those magic, and escaping ! as [!] isn't valid,
     // because [!]] is a valid glob class meaning not ']'.
-    if (magicalBraces) {
-        return windowsPathsNoEscape ?
-            s.replace(/[?*()[\]{}]/g, '[$&]')
-            : s.replace(/[?*()[\]\\{}]/g, '\\$&');
+    // However, at the start of the pattern, '!' negates the pattern and
+    // '#' makes it a comment, so the first character is handled below.
+    const e = magicalBraces ?
+        windowsPathsNoEscape ? s.replace(/[?*()[\]{}]/g, '[$&]')
+            : s.replace(/[?*()[\]\\{}]/g, '\\$&')
+        : windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, '[$&]')
+            : s.replace(/[?*()[\]\\]/g, '\\$&');
+    const c = e.charAt(0);
+    if (c === '#') {
+        return (windowsPathsNoEscape ? '[#]' : '\\#') + e.slice(1);
+    }
+    if (c === '!') {
+        // '[!]' can not be used, because '[!' starts a negated class, and
+        // '\' is a path separator in windowsPathsNoEscape mode. '@(!)'
+        // matches only '!'. If extglobs are disabled with `noext`, it
+        // matches nothing, rather than everything.
+        return (windowsPathsNoEscape ? '@(!)' : '\\!') + e.slice(1);
     }
-    return windowsPathsNoEscape ?
-        s.replace(/[?*()[\]]/g, '[$&]')
-        : s.replace(/[?*()[\]\\]/g, '\\$&');
+    return e;
 };
 //# sourceMappingURL=escape.js.map
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.js.map
index 4740508f687a904a44be71d42e0e0bf1438ea215..984fff8e780a4fbfd7d9c0eadc3e2c5f01dba11e 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.js.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/escape.js.map
@@ -1 +1 @@
-{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,KAAK,MAC+C,EAAE,EACxE,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC;YACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAA;IACzC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character.  In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n */\nexport const escape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = false,\n  }: Pick = {},\n) => {\n  // don't need to escape +@! because we escape the parens\n  // that make those magic, and escaping ! as [!] isn't valid,\n  // because [!]] is a valid glob class meaning not ']'.\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/[?*()[\\]{}]/g, '[$&]')\n      : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/[?*()[\\]]/g, '[$&]')\n    : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,KAAK,MAC+C,EAAE,EACxE,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,oEAAoE;IACpE,mEAAmE;IACnE,MAAM,CAAC,GACL,aAAa,CAAC,CAAC;QACb,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC;YACxD,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,MAAM,CAAC;QACvC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;YACxD,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;IACrC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;IACrB,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;QACd,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC5D,CAAC;IACD,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;QACd,kEAAkE;QAClE,+DAA+D;QAC/D,8DAA8D;QAC9D,2CAA2C;QAC3C,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAC7D,CAAC;IACD,OAAO,CAAC,CAAA;AACV,CAAC,CAAA","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character.  In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n *\n * If the {@link MinimatchOptions.magicalBraces} option is used,\n * then braces (`{` and `}`) will be escaped.\n *\n * A leading `#` or `!` is escaped as well, so that the result is never a\n * comment or a negated pattern. In `windowsPathsNoEscape` mode, a leading\n * `!` is written as `@(!)`, because `[!` starts a negated class.\n */\nexport const escape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = false,\n  }: Pick = {},\n) => {\n  // don't need to escape +@! because we escape the parens\n  // that make those magic, and escaping ! as [!] isn't valid,\n  // because [!]] is a valid glob class meaning not ']'.\n  // However, at the start of the pattern, '!' negates the pattern and\n  // '#' makes it a comment, so the first character is handled below.\n  const e =\n    magicalBraces ?\n      windowsPathsNoEscape ? s.replace(/[?*()[\\]{}]/g, '[$&]')\n      : s.replace(/[?*()[\\]\\\\{}]/g, '\\\\$&')\n    : windowsPathsNoEscape ? s.replace(/[?*()[\\]]/g, '[$&]')\n    : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n  const c = e.charAt(0)\n  if (c === '#') {\n    return (windowsPathsNoEscape ? '[#]' : '\\\\#') + e.slice(1)\n  }\n  if (c === '!') {\n    // '[!]' can not be used, because '[!' starts a negated class, and\n    // '\\' is a path separator in windowsPathsNoEscape mode. '@(!)'\n    // matches only '!'. If extglobs are disabled with `noext`, it\n    // matches nothing, rather than everything.\n    return (windowsPathsNoEscape ? '@(!)' : '\\\\!') + e.slice(1)\n  }\n  return e\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.d.ts b/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.d.ts
index 7e1fc2edaadbe09033faefbd7363f0cba109bafc..4a485677d293d846ea4f5dade134d166da200f16 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.d.ts
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.d.ts
@@ -1,4 +1,4 @@
-import { AST } from './ast.js';
+import { Matcher, type Form } from '@isaacs/nonrecursive-glob-match';
 export type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
 export interface MinimatchOptions {
     /** do not expand `{x,y}` style braces */
@@ -7,8 +7,6 @@ export interface MinimatchOptions {
     nocomment?: boolean;
     /** do not treat patterns starting with `!` as a negation */
     nonegate?: boolean;
-    /** print LOTS of debugging output */
-    debug?: boolean;
     /** treat `**` the same as `*` */
     noglobstar?: boolean;
     /** do not expand extglobs like `+(a|b)` */
@@ -37,6 +35,11 @@ export interface MinimatchOptions {
     nocase?: boolean;
     /** ignore case only in wildcard patterns */
     nocaseMagicOnly?: boolean;
+    /**
+     * Normalize unicode in the pattern and in each portion of the
+     * tested paths, with this form. `true` means `'NFC'`.
+     */
+    normalize?: boolean | Form;
     /** consider braces to be "magic" for the purpose of `hasMagic` */
     magicalBraces?: boolean;
     /**
@@ -53,6 +56,9 @@ export interface MinimatchOptions {
     /**
      * A number indicating the level of optimization that should be done
      * to the pattern prior to parsing and using it for matches.
+     * At level 2 or higher, throws RangeError if splitting `**` and `..`
+     * would make more than `braceExpandMax` patterns, or add more than
+     * 1,000,000 path portions.
      */
     optimizationLevel?: number;
     /** operating system platform */
@@ -69,6 +75,10 @@ export interface MinimatchOptions {
     windowsNoMagicRoot?: boolean;
     /**
      * max number of `{...}` patterns to expand. Default 100_000.
+     *
+     * At `optimizationLevel` 2 or higher, this also limits the
+     * patterns made when `**` is followed by `..`. Over this limit,
+     * construction throws a RangeError.
      */
     braceExpandMax?: number;
     /**
@@ -78,27 +88,6 @@ export interface MinimatchOptions {
      * and can handle absurdly excessive patterns.
      */
     maxGlobstarRecursion?: number;
-    /**
-     * Max depth to traverse for nested extglobs like `*(a|b|c)`
-     *
-     * Default is 2, which is quite low, but any higher value
-     * swiftly results in punishing performance impacts. Note
-     * that this is *not*  relevant when the globstar types can
-     * be safely coalesced into a single set.
-     *
-     * For example, `*(a|@(b|c)|d)` would be flattened into
-     * `*(a|b|c|d)`. Thus, many common extglobs will retain good
-     * performance and  never hit this limit, even if they are
-     * excessively deep and complicated.
-     *
-     * If the limit is hit, then the extglob characters are simply
-     * not parsed, and the pattern effectively switches into
-     * `noextglob: true` mode for the contents of that nested
-     * sub-pattern. This will typically _not_ result in a match,
-     * but is considered a valid trade-off for security and
-     * performance.
-     */
-    maxExtglobRecursion?: number;
 }
 export declare const minimatch: {
     (p: string, pattern: string, options?: MinimatchOptions): boolean;
@@ -107,9 +96,7 @@ export declare const minimatch: {
     filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
     defaults: (def: MinimatchOptions) => typeof minimatch;
     braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
-    makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
     match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
-    AST: typeof AST;
     Minimatch: typeof Minimatch;
     escape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick) => string;
     unescape: (s: string, { windowsPathsNoEscape, magicalBraces, }?: Pick) => string;
@@ -120,13 +107,46 @@ export declare const GLOBSTAR: unique symbol;
 export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
 export declare const defaults: (def: MinimatchOptions) => typeof minimatch;
 export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
-export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
 export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
-export type MMRegExp = RegExp & {
-    _src?: string;
-    _glob?: string;
+/**
+ * A path that Minimatch#match split, with the settings that the split
+ * depends on. `resolved` is the parts after optimizationLevel 2 has
+ * resolved `.` and `..` in them, which only depends on the same
+ * settings, once a level 2 Minimatch has needed them.
+ */
+export type SplitPath = {
+    f: string;
+    isWindows: boolean;
+    preserveMultipleSlashes: boolean;
+    normalize: Form | undefined;
+    parts: string[];
+    resolved?: string[];
+};
+export type ParseReturnFiltered = string | Matcher | typeof GLOBSTAR;
+/**
+ * The rows that Minimatch#match can match without splitting the path:
+ * `**` and one more portion (`tail`), a portion with `**` on each side
+ * of it (`mid`), a portion and then `**` (`head`), or one portion that
+ * matches the basename of the path, with matchBase (`base`).
+ */
+export type RowShape = 'tail' | 'mid' | 'head' | 'base';
+/**
+ * The separators that a path has: only `/`, only `\` (a Windows path
+ * with no `/`), or both. Scanning for the ones it has is faster.
+ */
+export type PathSeps = '/' | '\\' | 'both';
+/**
+ * A pattern row split on its first and last `**`, from a start
+ * index. Each body segment has the number of path portions that it
+ * and the ones after it need, to find the last index where it can
+ * start in a path.
+ */
+export type GlobstarParts = {
+    head: ParseReturn[];
+    body: ParseReturn[];
+    tail: ParseReturn[];
+    segments: [segment: ParseReturn[], need: number][];
 };
-export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
 export type ParseReturn = ParseReturnFiltered | false;
 export declare class Minimatch {
     #private;
@@ -147,28 +167,22 @@ export declare class Minimatch {
     platform: Platform;
     windowsNoMagicRoot: boolean;
     maxGlobstarRecursion: number;
-    regexp: false | null | MMRegExp;
     constructor(pattern: string, options?: MinimatchOptions);
     hasMagic(): boolean;
-    debug(..._: unknown[]): void;
     make(): void;
+    mergeRows(): void;
     preprocess(globParts: string[][]): string[][];
     adjascentGlobstarOptimize(globParts: string[][]): string[][];
     levelOneOptimize(globParts: string[][]): string[][];
-    levelTwoFileOptimize(parts: string | string[]): string[];
     firstPhasePreProcess(globParts: string[][]): string[][];
     secondPhasePreProcess(globParts: string[][]): string[][];
-    partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[];
     parseNegate(): void;
-    matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean;
     braceExpand(): string[];
     parse(pattern: string): ParseReturn;
-    makeRe(): false | MMRegExp;
-    slashSplit(p: string): string[];
     match(f: string, partial?: boolean): boolean;
     static defaults(def: MinimatchOptions): typeof Minimatch;
 }
-export { AST } from './ast.js';
 export { escape } from './escape.js';
 export { unescape } from './unescape.js';
+export type { Form };
 //# sourceMappingURL=index.d.ts.map
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.d.ts.map
index 7620db91cc81855821dded14c51fdfe9b0cd1d6a..0c296235759caedacd9eed307fab13dcb99b656f 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.d.ts.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAI9B,MAAM,MAAM,QAAQ,GAChB,KAAK,GACL,SAAS,GACT,QAAQ,GACR,SAAS,GACT,OAAO,GACP,OAAO,GACP,SAAS,GACT,OAAO,GACP,OAAO,GACP,QAAQ,GACR,QAAQ,CAAA;AAEZ,MAAM,WAAW,gBAAgB;IAC/B,yCAAyC;IACzC,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,2DAA2D;IAC3D,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,qCAAqC;IACrC,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,iCAAiC;IACjC,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,2CAA2C;IAC3C,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,4CAA4C;IAC5C,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,8DAA8D;IAC9D,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B;;;;;;;OAOG;IACH,OAAO,CAAC,EA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B/C,gBAAgB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IA4StC,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IA0G1C,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,EAAE;IAgDxD,WAAW;IAubX,WAAW;IAkDX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW;IAiEnC,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,UAAe;IAqFvC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,gBAAgB;CAGtC;AAED,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AACxC,YAAY,EAAE,IAAI,EAAE,CAAA"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.js b/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.js
index a5e6fa88fdc6d6ec05d26ab4975718824cbc8bdc..f8d6270b7bb3fc5530ea961ddf108fbf9a02dce9 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.js
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.js
@@ -1,73 +1,184 @@
 import { expand } from 'brace-expansion';
+import { Matcher } from '@isaacs/nonrecursive-glob-match';
 import { assertValidPattern } from './assert-valid-pattern.js';
-import { AST } from './ast.js';
 import { escape } from './escape.js';
 import { unescape } from './unescape.js';
-export const minimatch = (p, pattern, options = {}) => {
+const DEFAULT_BRACE_EXPAND_MAX = 100_000;
+const DEFAULT_GLOB_STAR_RECURSION_MAX = 200;
+// avoid the annoying deprecation flag lol
+const AWE_KEY = ('allowWindow' + 'sEscape');
+export const minimatch = (p, pattern, options) => {
     assertValidPattern(pattern);
     // shortcut: comments match nothing.
-    if (!options.nocomment && pattern.charAt(0) === '#') {
+    if (!options?.nocomment && pattern.charAt(0) === '#') {
         return false;
     }
-    return new Minimatch(pattern, options).match(p);
+    return cachedMinimatch(pattern, options).match(p);
 };
-// Optimized checking for the most common glob patterns.
-const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
-const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
-const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
-const starDotExtTestNocase = (ext) => {
-    ext = ext.toLowerCase();
-    return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
-};
-const starDotExtTestNocaseDot = (ext) => {
-    ext = ext.toLowerCase();
-    return (f) => f.toLowerCase().endsWith(ext);
-};
-const starDotStarRE = /^\*+\.\*+$/;
-const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
-const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
-const dotStarRE = /^\.\*+$/;
-const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
-const starRE = /^\*+$/;
-const starTest = (f) => f.length !== 0 && !f.startsWith('.');
-const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
-const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
-const qmarksTestNocase = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExt([$0]);
-    if (!ext)
-        return noext;
-    ext = ext.toLowerCase();
-    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
-};
-const qmarksTestNocaseDot = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExtDot([$0]);
-    if (!ext)
-        return noext;
-    ext = ext.toLowerCase();
-    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
-};
-const qmarksTestDot = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExtDot([$0]);
-    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+// The Minimatch objects that minimatch() used most recently, by options
+// and then by pattern. When the cache is full, it becomes the old one,
+// and the objects used from the old one are moved back to a new one.
+// So it keeps 256 to 512 objects.
+// The patterns can come from users, so the cache is also bounded by
+// the total weight of the objects (see cacheWeight()), and an object
+// that is too heavy is never kept. Otherwise a few unique patterns
+// with large brace expansions would fill the heap.
+let cache = new Map();
+let oldCache = new Map();
+let cacheSize = 0;
+let cacheTotalWeight = 0;
+const cacheMax = 256;
+const cacheMaxWeight = 1 << 15;
+const cacheMaxEntryWeight = 1 << 12;
+// About the memory that a compiled object keeps: the pattern and the
+// expanded patterns, of which each row in set is made.
+const cacheWeight = (mm) => {
+    let w = mm.pattern.length;
+    for (const s of mm.globSet) {
+        w += s.length + 1;
+        if (w > cacheMaxEntryWeight)
+            break;
+    }
+    return w;
 };
-const qmarksTest = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExt([$0]);
-    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+// tsc fails here if a new option is in neither type. Add it to
+// optionsKey() too.
+const allOptionsKeyed = true;
+void allOptionsKeyed;
+// 0, 1 or 2 for undefined, falsy or truthy.
+const tri = (v) => v === undefined ? 0
+    : v ? 2
+        : 1;
+// The weight of each boolean option's base-3 digit in the key. The
+// weights below 24 are for optimizationLevel (1), platform (3) and
+// windowsPathsNoEscape (12). tsc fails here if a boolean option is
+// not in the list.
+const booleanWeights = new Map(Object.keys({
+    nobrace: 0,
+    nocomment: 0,
+    nonegate: 0,
+    noglobstar: 0,
+    noext: 0,
+    nonull: 0,
+    partial: 0,
+    dot: 0,
+    nocase: 0,
+    nocaseMagicOnly: 0,
+    magicalBraces: 0,
+    matchBase: 0,
+    flipNegate: 0,
+    preserveMultipleSlashes: 0,
+    windowsNoMagicRoot: 0,
+}).map((k, i) => [k, 24 * 3 ** i]));
+// The cache key for a set of options. It is a number, unless an
+// option is set to a value that the number can not show, such as
+// normalize or an uncommon platform. Then it is a JSON string.
+// The defaults give 0, the same key as no options.
+// It only reads the keys that are set, so that the speed does not
+// depend on the shape of the options object.
+const optionsKey = (o) => {
+    let n = 0;
+    let wpe = false;
+    // inherited keys too, because Minimatch reads them
+    // oxlint-disable-next-line guard-for-in
+    for (const k in o) {
+        const v = o[k];
+        switch (k) {
+            // the same test as the Minimatch constructor
+            case 'windowsPathsNoEscape':
+                if (v)
+                    wpe = true;
+                break;
+            case AWE_KEY:
+                if (v === false)
+                    wpe = true;
+                break;
+            case 'platform': {
+                // the same test as the Minimatch constructor
+                const p = v || defaultPlatform;
+                if (p === defaultPlatform)
+                    break;
+                if (p === 'darwin')
+                    n += 3;
+                else if (p === 'win32')
+                    n += 6;
+                else if (p === 'linux')
+                    n += 9;
+                else
+                    return JSON.stringify(o);
+                break;
+            }
+            case 'optimizationLevel':
+                // The same tests as Minimatch: 1 when undefined, then >= 2,
+                // >= 1, or else 0. The default level 1 adds 0.
+                if (v === undefined)
+                    break;
+                n +=
+                    v >= 2 ? 1
+                        : v >= 1 ? 0
+                            : 2;
+                break;
+            case 'braceExpandMax':
+                if (v !== undefined && v !== DEFAULT_BRACE_EXPAND_MAX) {
+                    return JSON.stringify(o);
+                }
+                break;
+            case 'maxGlobstarRecursion':
+                if (v !== undefined && v !== DEFAULT_GLOB_STAR_RECURSION_MAX) {
+                    return JSON.stringify(o);
+                }
+                break;
+            case 'normalize':
+                if (v !== undefined)
+                    return JSON.stringify(o);
+                break;
+            default:
+                // unknown keys have no weight
+                n += (booleanWeights.get(k) ?? 0) * tri(v);
+        }
+    }
+    return wpe ? n + 12 : n;
 };
-const qmarksTestNoExt = ([$0]) => {
-    const len = $0.length;
-    return (f) => f.length === len && !f.startsWith('.');
+// A copy, so a later change to the options can not change it. Unlike
+// a spread, it keeps the inherited keys, which optionsKey() and the
+// Minimatch constructor also read.
+const copyOptions = (o) => {
+    const copy = {};
+    // oxlint-disable-next-line guard-for-in
+    for (const k in o)
+        copy[k] = o[k];
+    return copy;
 };
-const qmarksTestNoExtDot = ([$0]) => {
-    const len = $0.length;
-    return (f) => f.length === len && f !== '.' && f !== '..';
+const cachedMinimatch = (pattern, options) => {
+    const key = options ? optionsKey(options) : 0;
+    let mm = cache.get(key)?.get(pattern);
+    if (mm)
+        return mm;
+    mm =
+        oldCache.get(key)?.get(pattern) ??
+            new Minimatch(pattern, copyOptions(options));
+    const weight = cacheWeight(mm);
+    // too big to keep, so it is compiled again each time
+    if (weight > cacheMaxEntryWeight)
+        return mm;
+    if (cacheSize >= cacheMax ||
+        cacheTotalWeight + weight > cacheMaxWeight) {
+        oldCache = cache;
+        cache = new Map();
+        cacheSize = 0;
+        cacheTotalWeight = 0;
+    }
+    let byPattern = cache.get(key);
+    if (!byPattern)
+        cache.set(key, (byPattern = new Map()));
+    byPattern.set(pattern, mm);
+    cacheSize++;
+    cacheTotalWeight += weight;
+    return mm;
 };
 /* c8 ignore start */
 const defaultPlatform = (typeof process === 'object' && process ?
-    (typeof process.env === 'object' &&
-        process.env &&
-        process.env.__MINIMATCH_TESTING_PLATFORM__) ||
-        process.platform
+    process.env?.__MINIMATCH_TESTING_PLATFORM__ || process.platform
     : 'posix');
 const path = {
     win32: { sep: '\\' },
@@ -78,19 +189,10 @@ export const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep
 minimatch.sep = sep;
 export const GLOBSTAR = Symbol('globstar **');
 minimatch.GLOBSTAR = GLOBSTAR;
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-const qmark = '[^/]';
-// * => any number of characters
-const star = qmark + '*?';
-// ** when dots are allowed.  Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
-export const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
+export const filter = (pattern, options) => {
+    let mm;
+    return (p) => (mm ??= cachedMinimatch(pattern, options)).match(p);
+};
 minimatch.filter = filter;
 const ext = (a, b = {}) => Object.assign({}, a, b);
 export const defaults = (def) => {
@@ -108,21 +210,10 @@ export const defaults = (def) => {
                 return orig.defaults(ext(def, options)).Minimatch;
             }
         },
-        AST: class AST extends orig.AST {
-            /* c8 ignore start */
-            constructor(type, parent, options = {}) {
-                super(type, parent, ext(def, options));
-            }
-            /* c8 ignore stop */
-            static fromGlob(pattern, options = {}) {
-                return orig.AST.fromGlob(pattern, ext(def, options));
-            }
-        },
         unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
         escape: (s, options = {}) => orig.escape(s, ext(def, options)),
         filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
         defaults: (options) => orig.defaults(ext(def, options)),
-        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
         braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
         match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
         sep: orig.sep,
@@ -148,22 +239,56 @@ export const braceExpand = (pattern, options = {}) => {
         // shortcut. no need to expand.
         return [pattern];
     }
-    return expand(pattern, { max: options.braceExpandMax });
+    // brace-expansion turns each escaped backslash '\\' into a single '\',
+    // which then escapes the next character instead, and can turn an
+    // escaped magic character (for example '\\\*') into a live one.
+    // Double every pair, so an escaped backslash comes back out still
+    // escaped. The parity of each run of backslashes is unchanged.
+    let p = pattern.replace(/\\\\/g, '\\\\\\\\');
+    // brace-expansion does not know about [...] classes. In
+    // windowsPathsNoEscape mode, escape() writes a literal brace as '[{]'
+    // or '[}]'. Escape the brace for brace-expansion, which removes that
+    // backslash again, leaving '[{]' or '[}]'.
+    if (options.windowsPathsNoEscape || options[AWE_KEY] === false) {
+        p = p.replace(/\[([{}])\]/g, '[\\$1]');
+    }
+    return expand(p, { max: options.braceExpandMax });
 };
 minimatch.braceExpand = braceExpand;
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion.  Otherwise, any series
-// of * is equivalent to a single *.  Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-export const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
-minimatch.makeRe = makeRe;
+// A numeric range with at least this many values is matched as one
+// pattern portion, rather than expanded. For a glob walk, that is
+// one directory read, in place of a stat for each value.
+const RANGE_MIN = 100;
+// a {lo..hi} range that is not escaped, and not a ${...} variable
+const rangeRe = /(? {
+    const stack = [];
+    for (let i = 0; i < portion.length; i++) {
+        const c = portion.charAt(i);
+        if (c === '\\') {
+            i++;
+        }
+        else if (c === mark) {
+            if (stack.some(t => t !== '@' && t !== '?'))
+                return true;
+        }
+        else if (portion.charAt(i + 1) === '(' && '!?+*@'.includes(c)) {
+            stack.push(c);
+            i++;
+        }
+        else if (c === ')') {
+            stack.pop();
+        }
+    }
+    return false;
+};
 export const match = (list, pattern, options = {}) => {
     const mm = new Minimatch(pattern, options);
     list = list.filter(f => mm.match(f));
@@ -173,9 +298,228 @@ export const match = (list, pattern, options = {}) => {
     return list;
 };
 minimatch.match = match;
-// replace stuff like \* with *
 const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
-const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// Index of the `]` that closes the class that starts at `start`,
+// or -1 if it is not closed. Posix classes such as `[:alpha:]` are
+// not skipped, so this can find a `]` before the real end. That
+// only makes a class look less like a literal.
+const classEnd = (pattern, start) => {
+    let i = start + 1;
+    if (pattern.charAt(i) === '!' || pattern.charAt(i) === '^')
+        i++;
+    let sawStart = false;
+    for (; i < pattern.length; i++) {
+        const c = pattern.charAt(i);
+        if (c === ']' && sawStart)
+            return i;
+        sawStart = true;
+        if (c === '\\')
+            i++;
+    }
+    return -1;
+};
+// If a path portion pattern has no magic, return the string it
+// matches. Otherwise, return undefined. This can report magic for
+// a pattern that is in fact literal (eg, `[]`), but never the
+// reverse, so a string result is always safe to compare directly.
+const literal = (pattern, noext) => {
+    if (!noext && (pattern === '+()' || pattern === '@()'))
+        return pattern;
+    let lit = '';
+    for (let i = 0; i < pattern.length; i++) {
+        const c = pattern.charAt(i);
+        if (c === '\\') {
+            // a trailing \ is a literal \
+            lit += pattern.charAt(++i) || c;
+        }
+        else if (c === '*' || c === '?') {
+            return undefined;
+        }
+        else if (c === '[') {
+            const close = classEnd(pattern, i);
+            if (close === -1) {
+                // not closed, so the [ is a literal
+                lit += c;
+                continue;
+            }
+            // a class of one char, such as `[*]` or `[\b]`, is a literal
+            let body = pattern.slice(i + 1, close);
+            if (body.startsWith('\\'))
+                body = body.slice(1);
+            if ([...body].length !== 1 || '!^'.includes(pattern.charAt(i + 1))) {
+                return undefined;
+            }
+            lit += body;
+            i = close;
+        }
+        else if (!noext &&
+            '+@!'.includes(c) &&
+            pattern.charAt(i + 1) === '(' &&
+            pattern.includes(')', i + 2)) {
+            return undefined;
+        }
+        else {
+            lit += c;
+        }
+    }
+    return lit;
+};
+// The matching engine compiles and walks extglobs recursively, so a
+// path portion with very many extglobs (nested, such as `*(*(*(a)))`,
+// or in a row, such as `?(a)?(a)?(a)`) can exhaust the call stack.
+// Portions with more than this many extglobs are rejected.
+const MAX_EXTGLOBS = 256;
+// The number of extglob openers, such as `*(`, in a path portion
+// pattern. Chars in a class are counted too, so this can be more than
+// the number of extglobs, but never less.
+const extglobCount = (pattern) => {
+    let n = 0;
+    for (let i = 0; i < pattern.length - 1; i++) {
+        const c = pattern.charAt(i);
+        if (c === '\\') {
+            i++;
+        }
+        else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') {
+            n++;
+            i++;
+        }
+    }
+    return n;
+};
+const assertValidExtglobs = (pattern) => {
+    if (extglobCount(pattern) > MAX_EXTGLOBS) {
+        throw new TypeError('pattern has too many extglobs');
+    }
+};
+// True if the portion pattern has the same meaning as an alternative
+// inside `@(...)`. It must not have a `|` or `)` that is not in a
+// closed extglob (those are literal at the top level), an extglob
+// that is not closed (the `)` of the `@(...)` would close it), or a
+// trailing `\` (it would escape the next `|`). A pattern that is
+// only an empty extglob, such as `?()`, is literal on its own, but
+// not in `@(...)`. Posix classes such as `[:alpha:]` can hide a `]`
+// from classEnd, so patterns with them are not merged.
+const extSafe = (pattern) => {
+    if (/^[?*+@]\(\)$/.test(pattern) || pattern.includes('[:'))
+        return false;
+    let depth = 0;
+    for (let i = 0; i < pattern.length; i++) {
+        const c = pattern.charAt(i);
+        if (c === '\\') {
+            if (++i === pattern.length)
+                return false;
+        }
+        else if (c === '[') {
+            const close = classEnd(pattern, i);
+            if (close !== -1)
+                i = close;
+        }
+        else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') {
+            depth++;
+            i++;
+        }
+        else if (c === ')') {
+            if (!depth--)
+                return false;
+        }
+        else if (c === '|' && !depth) {
+            return false;
+        }
+    }
+    return !depth;
+};
+// The last path that Minimatch#match split, and its parts. A path is
+// often tested against many patterns in a row (such as a list of
+// ignore patterns), so this saves splitting it again. The parts are
+// never changed, so they can be shared.
+let lastSplit;
+// The last path that Minimatch#match checked before splitting it. If
+// the same path is checked again, it is being tested against many
+// patterns, so it is split and the parts are kept for the others.
+let lastChecked;
+// true if a pattern portion that is not ** matches a path portion.
+// An empty path portion only matches an empty pattern portion. A path
+// portion never has a `/`, so the Matcher does not need to check it.
+const portionMatch = (p, f) => typeof p === 'string' ? f === p : f !== '' && p.testUnchecked(f);
+// Where the last portion of a row matches in a path: the start of the
+// last portion of the path, or of the one before a trailing `/`. -1 if
+// it matches neither.
+const endIndex = (p, last, lastStart, prev, prevStart) => portionMatch(p, last) ? lastStart
+    : prev !== undefined && portionMatch(p, prev) ? prevStart
+        : -1;
+const isDots = (p) => p === '.' || p === '..';
+// a Windows drive letter portion, like `c:`
+const isDrive = (p) => typeof p === 'string' && /^[a-z]:$/i.test(p);
+// true for the `UNC` portion of a long UNC root, //?/UNC/host/share
+const isLongUNC = (p) => typeof p === 'string' && /^unc$/i.test(p);
+// The index of the host in a row or split path that starts with a
+// Windows UNC root: 2 for `//host/share`, and 4 for
+// `//?/UNC/host/share`. Otherwise -1. `//?/c:` is not one.
+const uncHost = (p) => {
+    if (p[0] !== '' || p[1] !== '')
+        return -1;
+    const h = p[2] !== '?' ? 2
+        : isLongUNC(p[3]) ? 4
+            : -1;
+    const host = p[h];
+    const share = p[h + 1];
+    return (h !== -1 &&
+        host !== undefined &&
+        host !== '' &&
+        host !== GLOBSTAR &&
+        share !== undefined &&
+        share !== '' &&
+        share !== GLOBSTAR) ?
+        h
+        : -1;
+};
+// true if ** can walk the path portion: not `.` or `..`, and not a
+// dotfile unless `dot` is set
+const walkable = (p, dot) => !isDots(p) && (dot || !p.startsWith('.'));
+// True if a portion of the path from `start` to `end` can not be
+// walked by **: one that starts with `.`, or with `dot`, one that is
+// `.` or `..`. `start` is the start of a portion, and `end` is the end
+// of the path, or just after a separator.
+const dotPortion = (f, start, end, dot, sep) => {
+    for (let k = start; k < end;) {
+        if (f.charCodeAt(k) === 46) {
+            if (!dot)
+                return true;
+            const n = f.charCodeAt(k + 1) === 46 ? k + 2 : k + 1;
+            if (n >= end || isSep(f.charCodeAt(n), sep))
+                return true;
+        }
+        // the start of the next portion, after any run of separators
+        const s = nextSep(f, k, sep);
+        if (s === -1)
+            return false;
+        k = s + 1;
+        while (k < end && isSep(f.charCodeAt(k), sep))
+            k++;
+    }
+    return false;
+};
+const isSep = (c, sep) => sep === '/' ? c === 47
+    : sep === '\\' ? c === 92
+        : c === 47 || c === 92;
+// the index of the first separator at or after `from`, or -1
+const nextSep = (f, from, sep) => {
+    if (sep !== 'both')
+        return f.indexOf(sep, from);
+    const s = f.indexOf('/', from);
+    const b = f.indexOf('\\', from);
+    return (s === -1 ? b
+        : b === -1 ? s
+            : Math.min(s, b));
+};
+// the index of the last separator at or before `from`, or -1
+const lastSep = (f, from, sep) => sep !== 'both' ?
+    f.lastIndexOf(sep, from)
+    : Math.max(f.lastIndexOf('/', from), f.lastIndexOf('\\', from));
+// What parse() returns in place of a Matcher while make() builds and
+// merges the rows. Most of the Matchers in rows that are merged would
+// never be used, so they are only made for the rows that are left.
+const PENDING = {};
 export class Minimatch {
     options;
     set;
@@ -194,24 +538,44 @@ export class Minimatch {
     platform;
     windowsNoMagicRoot;
     maxGlobstarRecursion;
-    regexp;
+    // the path can be checked against the last portion, and the string
+    // portions, of each row before it is split. See #canMatch.
+    #endCheck;
+    #literalCheck;
+    // level 2 resolves `.` and `..` portions in the path
+    #level2;
+    // the unicode normalization form, if any
+    #form;
+    // the string portions of each row in the set
+    #literals = [];
+    // the rows that #canMatch can match without splitting the path
+    #shapes = [];
+    // the rows whose last portion can be checked against the path's
+    #endRows = [];
+    // brace expansion can make the same portion in many rows, so they
+    // share one Matcher, and the states that it caches
+    #matchers = new Map();
+    // parse() returns PENDING in place of a Matcher
+    #pending = false;
+    // the char that marks numeric ranges in globSet, if any
+    #rangeMark;
+    // the GlobstarParts of each pattern row, by start index and partial
+    #globstarParts = new WeakMap();
     constructor(pattern, options = {}) {
         assertValidPattern(pattern);
         options = options || {};
         this.options = options;
-        this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
+        this.maxGlobstarRecursion =
+            options.maxGlobstarRecursion ?? DEFAULT_GLOB_STAR_RECURSION_MAX;
         this.pattern = pattern;
         this.platform = options.platform || defaultPlatform;
         this.isWindows = this.platform === 'win32';
-        // avoid the annoying deprecation flag lol
-        const awe = ('allowWindow' + 'sEscape');
         this.windowsPathsNoEscape =
-            !!options.windowsPathsNoEscape || options[awe] === false;
+            !!options.windowsPathsNoEscape || options[AWE_KEY] === false;
         if (this.windowsPathsNoEscape) {
             this.pattern = this.pattern.replace(/\\/g, '/');
         }
         this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
-        this.regexp = null;
         this.negate = false;
         this.nonegate = !!options.nonegate;
         this.comment = false;
@@ -225,8 +589,81 @@ export class Minimatch {
         this.globSet = [];
         this.globParts = [];
         this.set = [];
-        // make the set of regexps etc.
+        this.#endCheck = !this.preserveMultipleSlashes;
+        this.#level2 = (options.optimizationLevel ?? 1) >= 2;
+        const n = options.normalize;
+        this.#form = n === true ? 'NFC' : n || undefined;
+        // make the set of Matchers etc.
         this.make();
+        // On Windows, the portions of a row up to its drive letter or UNC
+        // share are skipped or compared without case, if the path has one
+        // too. So the checks only use the portions after it.
+        const drives = this.set.map(row => this.#rootIndex(row));
+        this.#endRows = this.set.map((row, r) => this.#endCheck && row.length - 1 > drives[r]);
+        // with the end check, the last portion is already checked
+        this.#literals = this.set.map((row, r) => {
+            const end = this.#endRows[r] ? row.length - 1 : row.length;
+            const lits = row
+                .slice(drives[r] + 1, end)
+                .filter((p) => typeof p === 'string' && !!p);
+            return [...new Set(lits)];
+        });
+        this.#literalCheck = this.#literals.some(l => l.length);
+        this.#shapes = this.set.map((row, r) => {
+            const [p0, p1, p2] = row;
+            if (this.#endRows[r] && row.length === 2) {
+                if (p0 === GLOBSTAR && p1 !== GLOBSTAR)
+                    return 'tail';
+            }
+            // the basename of a path that is split on / is its last portion,
+            // or the one before a trailing /, the same as the end check
+            if (this.#endRows[r] &&
+                options.matchBase &&
+                row.length === 1 &&
+                p0 !== GLOBSTAR &&
+                p0 !== '') {
+                return 'base';
+            }
+            // the portion must not be a root, or '', which can be a
+            // different portion on Windows (where //x paths get an extra '')
+            if (!this.#endCheck || drives[r] !== -1)
+                return undefined;
+            if (row.length === 3 &&
+                p0 === GLOBSTAR &&
+                p2 === GLOBSTAR &&
+                p1 !== GLOBSTAR &&
+                p1 !== '' &&
+                // the portion between is only matched below this limit
+                this.maxGlobstarRecursion > 0) {
+                return 'mid';
+            }
+            if (row.length === 2 &&
+                p1 === GLOBSTAR &&
+                p0 !== GLOBSTAR &&
+                p0 !== '') {
+                return 'head';
+            }
+            return undefined;
+        });
+    }
+    // a string portion of a pattern, normalized if the option is set
+    #norm(p) {
+        return this.#form ? p.normalize(this.#form) : p;
+    }
+    // On Windows, the index of the last root portion of a row, as
+    // #matchRow finds it: 0 for `c:/...`, 3 for `//?/c:/...` and
+    // `//host/share/...`, and 5 for `//?/UNC/host/share/...`. Otherwise
+    // -1.
+    #rootIndex(row) {
+        if (!this.isWindows)
+            return -1;
+        if (isDrive(row[0]))
+            return 0;
+        const uncDrive = row[0] === '' && row[1] === '' && row[2] === '?' && isDrive(row[3]);
+        if (uncDrive)
+            return 3;
+        const h = uncHost(row);
+        return h === -1 ? -1 : h + 1;
     }
     hasMagic() {
         if (this.options.magicalBraces && this.set.length > 1) {
@@ -240,7 +677,6 @@ export class Minimatch {
         }
         return false;
     }
-    debug(..._) { }
     make() {
         const pattern = this.pattern;
         const options = this.options;
@@ -256,46 +692,45 @@ export class Minimatch {
         // step 1: figure out negation, etc.
         this.parseNegate();
         // step 2: expand braces
-        this.globSet = [...new Set(this.braceExpand())];
-        if (options.debug) {
-            //oxlint-disable-next-line no-console
-            this.debug = (...args) => console.error(...args);
-        }
-        this.debug(this.pattern, this.globSet);
+        this.globSet = [...new Set(this.#expandBraces())];
         // step 3: now we have a set, so turn each one into a series of
         // path-portion matching patterns.
-        // These will be regexps, except in the case of "**", which is
+        // These will be Matchers, except in the case of "**", which is
         // set to the GLOBSTAR object for globstar behavior,
         // and will not contain any / characters
         //
         // First, we preprocess to make the glob pattern sets a bit simpler
         // and deduped.  There are some perf-killing patterns that can cause
         // problems with a glob walk, but we can simplify them down a bit.
-        const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
+        const rawGlobParts = this.globSet.map(s => this.#slashSplit(s));
         this.globParts = this.preprocess(rawGlobParts);
-        this.debug(this.pattern, this.globParts);
-        // glob --> regexps
+        // glob --> Matchers
+        this.#pending = true;
         let set = this.globParts.map((s, _, __) => {
             if (this.isWindows && this.windowsNoMagicRoot) {
-                // check if it's a drive or unc path.
+                // check if it's a drive or unc path. The root of a long UNC
+                // path, //?/UNC/host/share, is 6 portions.
+                const n = s[2] === '?' && isLongUNC(s[3]) ? 6 : 4;
                 const isUNC = s[0] === '' &&
                     s[1] === '' &&
                     (s[2] === '?' || !globMagic.test(s[2])) &&
-                    !globMagic.test(s[3]);
+                    s.slice(3, n).every(p => !globMagic.test(p));
                 const isDrive = /^[a-z]:/i.test(s[0]);
                 if (isUNC) {
                     return [
-                        ...s.slice(0, 4),
-                        ...s.slice(4).map(ss => this.parse(ss)),
+                        ...s.slice(0, n).map(p => this.#norm(p)),
+                        ...s.slice(n).map(ss => this.parse(ss)),
                     ];
                 }
                 else if (isDrive) {
-                    return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
+                    return [
+                        this.#norm(s[0]),
+                        ...s.slice(1).map(ss => this.parse(ss)),
+                    ];
                 }
             }
             return s.map(ss => this.parse(ss));
         });
-        this.debug(this.pattern, set);
         // filter out everything that didn't compile properly.
         this.set = set.filter(s => s.indexOf(false) === -1);
         // do not treat the ? in UNC paths as magic
@@ -305,13 +740,135 @@ export class Minimatch {
                 if (p[0] === '' &&
                     p[1] === '' &&
                     this.globParts[i][2] === '?' &&
-                    typeof p[3] === 'string' &&
-                    /^[a-z]:$/i.test(p[3])) {
+                    (isDrive(p[3]) || isLongUNC(this.globParts[i][3]))) {
+                    if (isLongUNC(this.globParts[i][3]))
+                        p[3] = 'UNC';
                     p[2] = '?';
                 }
             }
         }
-        this.debug(this.pattern, this.set);
+        // with noext, `@(...)` would be literal
+        if (!options.noext)
+            this.mergeRows();
+        this.#pending = false;
+        this.set.forEach((row, i) => {
+            for (let k = 0; k < row.length; k++) {
+                if (row[k] === PENDING) {
+                    row[k] = this.parse(this.globParts[i][k]);
+                }
+            }
+        });
+    }
+    // Merge rows that only differ in one portion, where each of them
+    // is a Matcher, into one row that matches any of them with
+    // `@(a|b|...)`. Then a path is only walked once for all of them,
+    // for example with `**/*.{js,ts}`.
+    mergeRows() {
+        let merged = true;
+        while (merged) {
+            merged = false;
+            // a single row cannot be merged with anything
+            if (this.set.length < 2)
+                return;
+            let keys = this.#mergeKeys();
+            const len = Math.max(0, ...this.set.map(r => r.length));
+            for (let k = 0; k < len; k++) {
+                // the rows that are the same other than at portion k, keyed
+                // by the ids of the parts before k and the parts after k,
+                // which are at most the number of rows
+                const groups = new Map();
+                const R = this.set.length + 1;
+                this.set.forEach((row, i) => {
+                    if (!(row[k] instanceof Matcher || row[k] === PENDING) ||
+                        !extSafe(this.globParts[i][k])) {
+                        return;
+                    }
+                    const { pre, suf } = keys[i];
+                    const key = pre[k] * R + suf[k + 1];
+                    const g = groups.get(key);
+                    if (g)
+                        g.push(i);
+                    else
+                        groups.set(key, [i]);
+                });
+                const drop = new Set();
+                for (const g of groups.values()) {
+                    if (g.length < 2)
+                        continue;
+                    const [first, ...rest] = g;
+                    const alts = g.map(i => this.globParts[i][k]);
+                    const glob = `@(${alts.join('|')})`;
+                    // merging is only an optimization, so leave the rows as they
+                    // are if the merged portion would have too many extglobs
+                    if (extglobCount(glob) > MAX_EXTGLOBS)
+                        continue;
+                    this.globParts[first][k] = glob;
+                    this.set[first][k] = this.parse(glob);
+                    for (const i of rest)
+                        drop.add(i);
+                }
+                if (drop.size) {
+                    merged = true;
+                    this.set = this.set.filter((_, i) => !drop.has(i));
+                    this.globParts = this.globParts.filter((_, i) => !drop.has(i));
+                    // every merge drops a row, so this happens at most once per row
+                    if (this.set.length < 2)
+                        return;
+                    keys = this.#mergeKeys();
+                }
+            }
+        }
+    }
+    // For each row, number ids for its prefixes and suffixes, such that
+    // pre[k] identifies parts[0..k) and suf[k] identifies parts[k..n).
+    // Two rows are the same other than at portion k exactly when they
+    // have the same pre[k] and suf[k + 1]. This is linear in the size of
+    // the rows, where joining the whole row for every k was quadratic.
+    #mergeKeys() {
+        const partIds = new Map();
+        const ids = this.globParts.map(parts => parts.map(s => {
+            let id = partIds.get(s);
+            if (id === undefined)
+                partIds.set(s, (id = partIds.size));
+            return id;
+        }));
+        // ids are only compared at the same k, so they are numbered per
+        // portion, with 0 for the empty prefix or suffix. Then they are
+        // at most the number of rows, and id * P + part id is a safe
+        // integer key for any set that fits in memory.
+        const P = partIds.size;
+        const len = Math.max(0, ...ids.map(r => r.length));
+        const keys = ids.map(r => ({
+            pre: [0],
+            suf: new Array(r.length + 1).fill(0),
+        }));
+        for (let k = 0; k < len; k++) {
+            const m = new Map();
+            ids.forEach((r, i) => {
+                if (k >= r.length)
+                    return;
+                const { pre } = keys[i];
+                const key = pre[k] * P + r[k];
+                let id = m.get(key);
+                if (id === undefined)
+                    m.set(key, (id = m.size + 1));
+                pre.push(id);
+            });
+        }
+        for (let k = len - 1; k >= 0; k--) {
+            const m = new Map();
+            ids.forEach((r, i) => {
+                if (k >= r.length)
+                    return;
+                const { suf } = keys[i];
+                const key = suf[k + 1] * P + r[k];
+                let id = m.get(key);
+                if (id === undefined)
+                    m.set(key, (id = m.size + 1));
+                suf[k] = id;
+            });
+        }
+        return keys;
     }
     // various transforms to equivalent pattern sets that are
     // faster to process in a filesystem walk.  The goal is to
@@ -364,13 +921,19 @@ export class Minimatch {
     // get rid of adjascent ** and resolve .. portions
     levelOneOptimize(globParts) {
         return globParts.map(parts => {
+            // .. can not remove the root of a Windows path
+            const root = this.#rootIndex(parts) + 1;
             parts = parts.reduce((set, part) => {
                 const prev = set[set.length - 1];
                 if (part === '**' && prev === '**') {
                     return set;
                 }
                 if (part === '..') {
-                    if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
+                    if (set.length > root &&
+                        prev &&
+                        prev !== '..' &&
+                        prev !== '.' &&
+                        prev !== '**') {
                         set.pop();
                         return set;
                     }
@@ -381,10 +944,214 @@ export class Minimatch {
             return parts.length === 0 ? [''] : parts;
         });
     }
-    levelTwoFileOptimize(parts) {
-        if (!Array.isArray(parts)) {
-            parts = this.slashSplit(parts);
+    // Check the path against each row before it is split. 'no' if no
+    // row can match, so it does not need to be split. 'yes' if a row of
+    // `**` and one more portion matches. 'maybe' if it must be split to
+    // know. None of this applies with partial, where the path can end
+    // before the row does.
+    //
+    // On Windows, `\` is a separator in the path too, and the portions of
+    // a row up to its drive letter or UNC share are not checked (see
+    // #rootIndex).
+    //
+    // Each string portion of a row must be a portion of the path, so the
+    // path must contain it. Level 2 can only take portions out of the
+    // path, so this is still true then.
+    //
+    // The last portion of a row must match the last portion of the path,
+    // or the one before a trailing `/` (as a/* and a/**/* match a/b/).
+    // This does not apply to rows that end in **, rows that end in a
+    // root, or preserveMultipleSlashes (which can leave more
+    // than one '' at the end). At level 2, it does not apply if that
+    // portion is `.` or `..`, which can be
+    // resolved away. Level 2 only takes other portions out of the
+    // middle of the path.
+    //
+    // A row of `**/x` then matches if the ** can walk the portions
+    // before the one that x matches, the same as #matchGlobstar. At
+    // level 2, this is only known if none of them are `.` or `..`, so
+    // that the path does not change when it is resolved.
+    #canMatch(f) {
+        const sep = !this.isWindows || !f.includes('\\') ? '/'
+            : f.includes('/') ? 'both'
+                : '\\';
+        // the portions that f.split(/\/+/) would end with, and where they
+        // start in f, found when a row needs them. `ends` is 0 until they
+        // are found, then 1, or -1 if they can not be used.
+        let ends = this.#endCheck ? 0 : -1;
+        let last = '';
+        let lastStart = 0;
+        let prev;
+        let prevStart = 0;
+        const dot = !!this.options.dot;
+        // A string compare is cheaper than includes(), and a Matcher test
+        // costs more, so the cheaper check goes first.
+        ROWS: for (let r = 0; r < this.set.length; r++) {
+            const row = this.set[r];
+            const p = row[row.length - 1];
+            let end = ends !== -1 && this.#endRows[r] && p !== GLOBSTAR;
+            if (end && ends === 0) {
+                const i = lastSep(f, f.length, sep);
+                lastStart = i + 1;
+                last = f.slice(lastStart);
+                if (last === '' && i >= 0) {
+                    let j = i;
+                    while (j > 0 && isSep(f.charCodeAt(j - 1), sep))
+                        j--;
+                    prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep) + 1;
+                    prev = f.slice(prevStart, j);
+                }
+                const resolves = this.#level2 &&
+                    (isDots(last) ||
+                        (last === '' && prev !== undefined && isDots(prev)));
+                ends = resolves ? -1 : 1;
+                end = !resolves;
+            }
+            let tailStart = -1;
+            if (end && typeof p === 'string') {
+                tailStart = endIndex(p, last, lastStart, prev, prevStart);
+                if (tailStart === -1)
+                    continue;
+            }
+            if (this.#literalCheck) {
+                for (const l of this.#literals[r]) {
+                    if (!f.includes(l))
+                        continue ROWS;
+                }
+            }
+            if (end && typeof p === 'object') {
+                tailStart = endIndex(p, last, lastStart, prev, prevStart);
+                if (tailStart === -1)
+                    continue;
+            }
+            const shape = this.#shapes[r];
+            if (shape === 'base' && end)
+                return 'yes';
+            if (shape === 'tail' && end) {
+                if (this.#level2 && dotPortion(f, 0, tailStart, true, sep)) {
+                    return 'maybe';
+                }
+                if (!dotPortion(f, 0, tailStart, dot, sep))
+                    return 'yes';
+                continue;
+            }
+            if (shape === 'mid' || shape === 'head') {
+                const m = this.#walk(f, row, shape === 'head', dot, sep);
+                if (m !== 'no')
+                    return m;
+                continue;
+            }
+            return 'maybe';
+        }
+        return 'no';
+    }
+    // Match a row of a known shape against the split path, the same as
+    // #matchGlobstar and #matchGlobStarBodySections do. None of these
+    // rows have a drive letter, so they start at the first portion.
+    #matchShape(file, row, shape) {
+        const dot = !!this.options.dot;
+        const n = file.length;
+        if (shape === 'head') {
+            // x, then at least one portion that ** can walk
+            if (n < 2 || !portionMatch(row[0], file[0])) {
+                return false;
+            }
+            for (let i = 1; i < n; i++)
+                if (!walkable(file[i], dot))
+                    return false;
+            return true;
+        }
+        const x = row[1];
+        if (shape === 'tail') {
+            // x is the last portion, or the one before a trailing ''
+            let t = n - 1;
+            if (!portionMatch(x, file[t])) {
+                if (file[t] !== '' || n === 1 || !portionMatch(x, file[--t])) {
+                    return false;
+                }
+            }
+            for (let i = 0; i < t; i++)
+                if (!walkable(file[i], dot))
+                    return false;
+            return true;
         }
+        // mid: the first x that ** can walk to, with a portion after it,
+        // and ** can walk all of those
+        for (let k = 0; k < n; k++) {
+            if (portionMatch(x, file[k]) && k + 1 < n) {
+                let i = k + 1;
+                while (i < n && walkable(file[i], dot))
+                    i++;
+                if (i === n)
+                    return true;
+            }
+            if (!walkable(file[k], dot))
+                return false;
+        }
+        return false;
+    }
+    // Match a row of `**/x/**` or `x/**` against the path, the same as
+    // #matchGlobstar and #matchGlobStarBodySections do once it is split.
+    // x must match a portion (the first one, for `x/**`), the ** before
+    // it must be able to walk the portions before that one, and there
+    // must be a portion after it, which the ** after it can walk. At
+    // level 2, this is only known if no portion is `.` or `..`.
+    #walk(f, row, head, dot, sep) {
+        if (this.#level2 && dotPortion(f, 0, f.length, true, sep))
+            return 'maybe';
+        const x = row[head ? 0 : 1];
+        // the last portion has none after it, so it can not be x
+        let s = 0;
+        for (let e = nextSep(f, s, sep); e !== -1; e = nextSep(f, s, sep)) {
+            // the start of the next portion
+            let next = e + 1;
+            while (next < f.length && isSep(f.charCodeAt(next), sep))
+                next++;
+            const hit = typeof x === 'string' ?
+                e - s === x.length && f.startsWith(x, s)
+                : e > s && x.testUnchecked(f.slice(s, e));
+            if (hit && !dotPortion(f, next, f.length, dot, sep))
+                return 'yes';
+            if (head || dotPortion(f, s, next, dot, sep))
+                return 'no';
+            s = next;
+        }
+        return 'no';
+    }
+    // the last split, if it was the same path with the same split
+    // settings
+    #cachedSplit(f) {
+        const last = lastSplit;
+        return (last?.f === f &&
+            last.isWindows === this.isWindows &&
+            last.preserveMultipleSlashes === this.preserveMultipleSlashes &&
+            last.normalize === this.#form) ?
+            last
+            : undefined;
+    }
+    // split a path for match(), and keep the parts for the next call
+    #split(f) {
+        const { isWindows, preserveMultipleSlashes } = this;
+        // windows: need to use /, not \
+        let parts = this.#slashSplit(isWindows ? f.split('\\').join('/') : f);
+        // normalize each portion, so that a char that normalizes to `/`
+        // does not make a new portion
+        const normalize = this.#form;
+        if (normalize)
+            parts = parts.map(p => p.normalize(normalize));
+        lastSplit = {
+            f,
+            isWindows,
+            preserveMultipleSlashes,
+            normalize,
+            parts,
+        };
+        return lastSplit;
+    }
+    // resolve `.` and `..` portions of a path, for level 2
+    #levelTwoFileOptimize(file) {
+        // work on a copy, so that the cached parts do not change
+        const parts = [...file];
         let didSomething = false;
         do {
             didSomething = false;
@@ -409,17 +1176,15 @@ export class Minimatch {
                 }
             }
             // 
/

/../ ->

/
-            let dd = 0;
+            // .. can not remove the root of a Windows path
+            const root = this.#rootIndex(parts) + 1;
+            let dd = root;
             while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                 const p = parts[dd - 1];
-                if (p &&
-                    p !== '.' &&
-                    p !== '..' &&
-                    p !== '**' &&
-                    !(this.isWindows && /^[a-z]:$/i.test(p))) {
+                if (p && p !== '.' && p !== '..' && p !== '**') {
                     didSomething = true;
                     parts.splice(dd - 1, 2);
-                    dd -= 2;
+                    dd = Math.max(dd - 2, root);
                 }
             }
         } while (didSomething);
@@ -444,6 +1209,13 @@ export class Minimatch {
     // **/*/ -> */**/ <== not valid because ** doesn't follow
     // this WOULD be allowed if ** did follow symlinks, or * didn't
     firstPhasePreProcess(globParts) {
+        // each **/.. split doubles the patterns, and adds a copy of the
+        // whole pattern. Throw if either gets too large. A partial split
+        // would match some paths and not others, depending on which rows
+        // the pass reached first.
+        const { braceExpandMax = DEFAULT_BRACE_EXPAND_MAX } = this.options;
+        let splitCells = 0;
+        const maxSplitCells = 1_000_000;
         let didSomething = false;
         do {
             didSomething = false;
@@ -474,11 +1246,18 @@ export class Minimatch {
                         p2 === '..') {
                         continue;
                     }
+                    // Check before changing parts or allocating the new row.
+                    const addedCells = parts.length - 1;
+                    if (globParts.length >= braceExpandMax ||
+                        splitCells + addedCells > maxSplitCells) {
+                        throw new RangeError(`optimizationLevel 2: too many patterns from '**/..'`);
+                    }
                     didSomething = true;
                     // edit parts in place, and push the new one
                     parts.splice(gs, 1);
                     const other = parts.slice(0);
                     other[gs] = '**';
+                    splitCells += addedCells;
                     globParts.push(other);
                     gs--;
                 }
@@ -503,7 +1282,9 @@ export class Minimatch {
                     }
                 }
                 // 
/

/../ ->

/
-                let dd = 0;
+                // .. can not remove the root of a Windows path
+                const root = this.#rootIndex(parts) + 1;
+                let dd = root;
                 while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                     const p = parts[dd - 1];
                     if (p && p !== '.' && p !== '..' && p !== '**') {
@@ -513,7 +1294,7 @@ export class Minimatch {
                         parts.splice(dd - 1, 2, ...splin);
                         if (parts.length === 0)
                             parts.push('');
-                        dd -= 2;
+                        dd = Math.max(dd - 2, root);
                     }
                 }
             }
@@ -521,73 +1302,59 @@ export class Minimatch {
         return globParts;
     }
     // second phase: multi-pattern dedupes
-    // {
/*/,
/

/} ->

/*/
     // {
/,
/} -> 
/
-    // {
/**/,
/} -> 
/**/
-    //
-    // {
/**/,
/**/

/} ->

/**/
-    // ^-- not valid because ** doens't follow symlinks
+    // {
/*/,
/

/} ->

/*/
     secondPhasePreProcess(globParts) {
-        for (let i = 0; i < globParts.length - 1; i++) {
-            for (let j = i + 1; j < globParts.length; j++) {
-                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
-                if (matched) {
-                    globParts[i] = [];
-                    globParts[j] = matched;
-                    break;
-                }
+        const keys = new Set();
+        const rows = globParts.filter(parts => {
+            const key = parts.join('/');
+            if (keys.has(key))
+                return false;
+            keys.add(key);
+            return true;
+        });
+        // A row is covered by another row that has `*` at some positions,
+        // and is the same at all others. Collect each distinct set of `*`
+        // positions, then look up each row with `*` put at those positions.
+        const stars = new Map();
+        for (const parts of rows) {
+            const s = [];
+            for (let i = 0; i < parts.length; i++) {
+                if (parts[i] === '*')
+                    s.push(i);
             }
+            if (s.length)
+                stars.set(s.join(','), s);
         }
-        return globParts.filter(gs => gs.length);
-    }
-    partsMatch(a, b, emptyGSMatch = false) {
-        let ai = 0;
-        let bi = 0;
-        let result = [];
-        let which = '';
-        while (ai < a.length && bi < b.length) {
-            if (a[ai] === b[bi]) {
-                result.push(which === 'b' ? b[bi] : a[ai]);
-                ai++;
-                bi++;
-            }
-            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
-                result.push(a[ai]);
-                ai++;
-            }
-            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
-                result.push(b[bi]);
-                bi++;
-            }
-            else if (a[ai] === '*' &&
-                b[bi] &&
-                (this.options.dot || !b[bi].startsWith('.')) &&
-                b[bi] !== '**') {
-                if (which === 'b')
-                    return false;
-                which = 'a';
-                result.push(a[ai]);
-                ai++;
-                bi++;
-            }
-            else if (b[bi] === '*' &&
-                a[ai] &&
-                (this.options.dot || !a[ai].startsWith('.')) &&
-                a[ai] !== '**') {
-                if (which === 'a')
+        // Each row is checked against each set of `*` positions, so skip
+        // this if there are too many. The patterns match the same paths
+        // either way.
+        if (!stars.size || rows.length * stars.size > 100_000)
+            return rows;
+        const { dot } = this.options;
+        return rows.filter(parts => {
+            for (const s of stars.values()) {
+                if (s[s.length - 1] >= parts.length)
+                    continue;
+                const c = [...parts];
+                let ok = true;
+                let changed = false;
+                for (const i of s) {
+                    const p = parts[i];
+                    if (p === '*')
+                        continue;
+                    if (!p || p === '**' || (!dot && p.startsWith('.'))) {
+                        ok = false;
+                        break;
+                    }
+                    c[i] = '*';
+                    changed = true;
+                }
+                if (ok && changed && keys.has(c.join('/')))
                     return false;
-                which = 'b';
-                result.push(b[bi]);
-                ai++;
-                bi++;
             }
-            else {
-                return false;
-            }
-        }
-        // if we fall out of the loop, it means they two are identical
-        // as long as their lengths match
-        return a.length === b.length && result;
+            return true;
+        });
     }
     parseNegate() {
         if (this.nonegate)
@@ -603,18 +1370,36 @@ export class Minimatch {
             this.pattern = pattern.slice(negateOffset);
         this.negate = negate;
     }
-    // set partial to true to test if, for example,
-    // "/a/b" matches the start of "/*/b/*/d"
-    // Partial means, if you run out of file before you run
-    // out of pattern, then that's fine, as long as all
-    // the parts match.
-    matchOne(file, pattern, partial = false) {
+    // Match the parts of a path against one row of the set. `resolved`
+    // is the parts after level 2 resolves `.` and `..` in them, or the
+    // same parts below level 2. Set partial to true to test if, for
+    // example, "/a/b" matches the start of "/*/b/*/d". Partial means, if
+    // you run out of file before you run out of pattern, then that's
+    // fine, as long as all the parts match.
+    #matchRow(file, resolved, pattern, partial) {
         let fileStartIndex = 0;
         let patternStartIndex = 0;
-        // UNC paths like //?/X:/... can match X:/... and vice versa
-        // Drive letters in absolute drive or unc paths are always compared
-        // case-insensitively.
-        if (this.isWindows) {
+        // UNC paths like //?/X:/... can match X:/... and vice versa, and
+        // //?/UNC/host/share/... can match //host/share/... and vice versa.
+        // Drive letters in absolute drive or unc paths, and the host and
+        // share of UNC paths, are always compared case-insensitively.
+        const fh = this.isWindows ? uncHost(resolved) : -1;
+        const ph = fh === -1 ? -1 : uncHost(pattern);
+        if (ph !== -1) {
+            const host = pattern[ph];
+            const share = pattern[ph + 1];
+            if (typeof host !== 'string' || typeof share !== 'string') {
+                // a host or share with magic is matched as usual
+                fileStartIndex = fh;
+                patternStartIndex = ph;
+            }
+            else if (resolved[fh].toLowerCase() === host.toLowerCase() &&
+                resolved[fh + 1].toLowerCase() === share.toLowerCase()) {
+                fileStartIndex = fh + 2;
+                patternStartIndex = ph + 2;
+            }
+        }
+        else if (this.isWindows) {
             const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
             const fileUNC = !fileDrive &&
                 file[0] === '' &&
@@ -639,47 +1424,27 @@ export class Minimatch {
                     file[fdi],
                     pattern[pdi],
                 ];
-                // start matching at the drive letter index of each
+                // the drives match, so start matching after them
                 if (fd.toLowerCase() === pd.toLowerCase()) {
-                    pattern[pdi] = fd;
-                    patternStartIndex = pdi;
-                    fileStartIndex = fdi;
+                    patternStartIndex = pdi + 1;
+                    fileStartIndex = fdi + 1;
                 }
             }
         }
-        // resolve and reduce . and .. portions in the file as well.
-        // don't need to do the second phase, because it's only one string[]
-        const { optimizationLevel = 1 } = this.options;
-        if (optimizationLevel >= 2) {
-            file = this.levelTwoFileOptimize(file);
-        }
+        // the drive letters are found in the parts before level 2 resolves
+        // them, and the match uses the resolved parts
+        file = resolved;
         if (pattern.includes(GLOBSTAR)) {
             return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
         }
         return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
     }
     #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
-        // split the pattern into head, tail, and middle of ** delimited parts
-        const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
-        const lastgs = pattern.lastIndexOf(GLOBSTAR);
-        // split the pattern up into globstar-delimited sections
-        // the tail has to be at the end, and the others just have
-        // to be found in order from the head.
-        const [head, body, tail] = partial ?
-            [
-                pattern.slice(patternIndex, firstgs),
-                pattern.slice(firstgs + 1),
-                [],
-            ]
-            : [
-                pattern.slice(patternIndex, firstgs),
-                pattern.slice(firstgs + 1, lastgs),
-                pattern.slice(lastgs + 1),
-            ];
+        const { head, body, tail, segments } = this.#getGlobstarParts(pattern, partial, patternIndex);
         // check the head, from the current file/pattern index.
         if (head.length) {
-            const fileHead = file.slice(fileIndex, fileIndex + head.length);
-            if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
+            const headEnd = fileIndex + head.length;
+            if (!this.#matchOne(file, head, partial, fileIndex, 0, headEnd)) {
                 return false;
             }
             fileIndex += head.length;
@@ -737,36 +1502,64 @@ export class Minimatch {
         // now we know that there's one or more body sections, which can
         // be matched anywhere from the 0 index (because the head was pruned)
         // through to the length-fileTailMatch index.
-        // split the body up into sections, and note the minimum index it can
-        // be found at (start with the length of all previous segments)
-        // [section, before, after]
-        const bodySegments = [[[], 0]];
-        let currentBody = bodySegments[0];
+        return !!this.#matchGlobStarBodySections(file, segments, file.length - fileTailMatch, fileIndex, 0, partial, 0, !!fileTailMatch, new Set());
+    }
+    // Split the pattern into head, tail, and middle of ** delimited
+    // parts. The tail has to be at the end, and the others just have to
+    // be found in order from the head. These only depend on the pattern
+    // row, so they are kept for the next path.
+    #getGlobstarParts(pattern, partial, patternIndex) {
+        let byStart = this.#globstarParts.get(pattern);
+        if (!byStart) {
+            byStart = [];
+            this.#globstarParts.set(pattern, byStart);
+        }
+        const key = patternIndex * 2 + (partial ? 1 : 0);
+        const found = byStart[key];
+        if (found)
+            return found;
+        const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
+        const lastgs = pattern.lastIndexOf(GLOBSTAR);
+        const head = pattern.slice(patternIndex, firstgs);
+        const body = pattern.slice(firstgs + 1, partial ? undefined : lastgs);
+        const tail = partial ? [] : pattern.slice(lastgs + 1);
+        // split the body up into sections, and note the number of
+        // portions that must come after the start of each one
+        const segments = [[[], 0]];
+        let current = segments[0];
         let nonGsParts = 0;
         const nonGsPartsSums = [0];
         for (const b of body) {
             if (b === GLOBSTAR) {
                 nonGsPartsSums.push(nonGsParts);
-                currentBody = [[], 0];
-                bodySegments.push(currentBody);
+                current = [[], 0];
+                segments.push(current);
             }
             else {
-                currentBody[0].push(b);
+                current[0].push(b);
                 nonGsParts++;
             }
         }
-        let i = bodySegments.length - 1;
-        const fileLength = file.length - fileTailMatch;
-        for (const b of bodySegments) {
-            b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
-        }
-        return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
+        // the portions in this section and the ones after it
+        segments.forEach((b, i) => {
+            b[1] = nonGsParts - nonGsPartsSums[i];
+        });
+        const parts = { head, body, tail, segments };
+        byStart[key] = parts;
+        return parts;
     }
     // return false for "nope, not matching"
     // return null for "not matching, cannot keep trying"
     #matchGlobStarBodySections(file, 
-    // pattern section, last possible position for it
-    bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
+    // pattern section, and the portions that it and the rest need
+    bodySegments, 
+    // the end of the file portions that the body can match
+    fileLength, fileIndex, bodyIndex, partial, globStarDepth, sawTail, 
+    // the places that a walk has already tried, as
+    // bodyIndex * (file.length + 1) + fileIndex. A walk from a place
+    // does the same no matter how it got there, and it only comes back
+    // if it found no match, so a walk that gets to one stops.
+    tried) {
         // take the first body segment, and walk from fileIndex to its "after"
         // value at the end
         // If it doesn't match at that position, we increment, until we hit
@@ -778,8 +1571,16 @@ export class Minimatch {
         // can't possibly be a valid matching condition.
         const bs = bodySegments[bodyIndex];
         if (!bs) {
-            // just make sure that there's no bad dots
-            for (let i = fileIndex; i < file.length; i++) {
+            // with partial, the body is the rest of the pattern, so it
+            // matches if no portions are left, or only the '' of a trailing
+            // / (as a/* matches a/b/). A ** at the end walks them as its own
+            // empty section.
+            if (partial) {
+                return (fileIndex >= fileLength ||
+                    (fileIndex === fileLength - 1 && file[fileIndex] === ''));
+            }
+            // just make sure that there's no bad dots before the tail
+            for (let i = fileIndex; i < fileLength; i++) {
                 sawTail = true;
                 const f = file[i];
                 if (f === '.' ||
@@ -790,19 +1591,29 @@ export class Minimatch {
             }
             return sawTail;
         }
-        // have a non-globstar body section to test
-        const [body, after] = bs;
+        // have a non-globstar body section to test, up to the last index
+        // where it can start
+        const [body, need] = bs;
+        // with partial, the path can end before the body does
+        const after = partial ? fileLength : fileLength - need;
         while (fileIndex <= after) {
-            const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
+            const key = bodyIndex * (file.length + 1) + fileIndex;
+            if (tried.has(key))
+                return false;
+            tried.add(key);
+            const m = this.#matchOne(file, body, partial, fileIndex, 0, fileIndex + body.length);
             // if limit exceeded, no match. intentional false negative,
             // acceptable break in correctness for security.
             if (m && globStarDepth < this.maxGlobstarRecursion) {
                 // match! see if the rest match. if so, we're done!
-                const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
+                const sub = this.#matchGlobStarBodySections(file, bodySegments, fileLength, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail, tried);
                 if (sub !== false) {
                     return sub;
                 }
             }
+            // the ** does not walk past the last place the body can start
+            if (fileIndex === after)
+                break;
             const f = file[fileIndex];
             if (f === '.' ||
                 f === '..' ||
@@ -814,21 +1625,20 @@ export class Minimatch {
         // walked off. no point continuing
         return partial || null;
     }
-    #matchOne(file, pattern, partial, fileIndex, patternIndex) {
+    #matchOne(file, pattern, partial, fileIndex, patternIndex, 
+    // only match the file portions before this index
+    fileEnd = file.length) {
         let fi;
         let pi;
         let pl;
         let fl;
         for (fi = fileIndex,
             pi = patternIndex,
-            fl = file.length,
+            fl = Math.min(fileEnd, file.length),
             pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
-            this.debug('matchOne loop');
             let p = pattern[pi];
             let f = file[fi];
-            this.debug(pattern, p, f);
             // should be impossible.
-            // some invalid regexp stuff in the set.
             /* c8 ignore start */
             if (p === false || p === GLOBSTAR) {
                 return false;
@@ -836,17 +1646,8 @@ export class Minimatch {
             /* c8 ignore stop */
             // something other than **
             // non-magic patterns just have to match exactly
-            // patterns with magic have been turned into regexps.
-            let hit;
-            if (typeof p === 'string') {
-                hit = f === p;
-                this.debug('string match', p, f, hit);
-            }
-            else {
-                hit = p.test(f);
-                this.debug('pattern match', p, f, hit);
-            }
-            if (!hit)
+            // patterns with magic have been turned into Matchers.
+            if (!portionMatch(p, f))
                 return false;
         }
         // Note: ending in / means that we'll get a final ""
@@ -855,9 +1656,8 @@ export class Minimatch {
         // If the file ends in /, then it can only match a
         // a pattern that ends in /, unless the pattern just
         // doesn't have any more for it. But, a/b/ should *not*
-        // match "a/b/*", even though "" matches against the
-        // [^/]*? pattern, except in partial mode, where it might
-        // simply not be reached yet.
+        // match "a/b/*", even though * can match "", except in
+        // partial mode, where it might simply not be reached yet.
         // However, a/b/ should still satisfy a/*
         // now either we fell off the end of the pattern, or we're done.
         if (fi === fl && pi === pl) {
@@ -888,6 +1688,49 @@ export class Minimatch {
     braceExpand() {
         return braceExpand(this.pattern, this.options);
     }
+    // Expand braces, except numeric ranges such as {0..999} with at
+    // least RANGE_MIN values. Each of those stays in its pattern as
+    // `0..999`, for the Matcher to test. If a range might
+    // be inside a [...] class, expand all of them instead.
+    #expandBraces() {
+        const { pattern } = this;
+        if (this.options.nobrace)
+            return this.braceExpand();
+        let code = 0xe000;
+        while (pattern.includes(String.fromCharCode(code))) {
+            if (++code > 0xf8ff)
+                return this.braceExpand();
+        }
+        const mark = String.fromCharCode(code);
+        let found = false;
+        const marked = pattern.replace(rangeRe, (m, lo, hi) => {
+            const a = Number(lo);
+            const b = Number(hi);
+            if (!Number.isSafeInteger(a) ||
+                !Number.isSafeInteger(b) ||
+                Math.abs(a - b) + 1 < RANGE_MIN) {
+                return m;
+            }
+            found = true;
+            return `${mark}${lo}..${hi}${mark}`;
+        });
+        if (!found)
+            return this.braceExpand();
+        const set = braceExpand(marked, this.options);
+        for (const p of set) {
+            for (const portion of p.split('/')) {
+                const c = portion.indexOf('[');
+                if (c !== -1 && c < portion.lastIndexOf(mark)) {
+                    return this.braceExpand();
+                }
+                if (!this.options.noext && inRepeatOrNegExt(portion, mark)) {
+                    return this.braceExpand();
+                }
+            }
+        }
+        this.#rangeMark = mark;
+        return set;
+    }
     parse(pattern) {
         assertValidPattern(pattern);
         const options = this.options;
@@ -896,139 +1739,37 @@ export class Minimatch {
             return GLOBSTAR;
         if (pattern === '')
             return '';
-        // far and away, the most common glob pattern parts are
-        // *, *.*, and *.  Add a fast check method for those.
-        let m;
-        let fastTest = null;
-        if ((m = pattern.match(starRE))) {
-            fastTest = options.dot ? starTestDot : starTest;
-        }
-        else if ((m = pattern.match(starDotExtRE))) {
-            fastTest = (options.nocase ?
-                options.dot ?
-                    starDotExtTestNocaseDot
-                    : starDotExtTestNocase
-                : options.dot ? starDotExtTestDot
-                    : starDotExtTest)(m[1]);
-        }
-        else if ((m = pattern.match(qmarksRE))) {
-            fastTest = (options.nocase ?
-                options.dot ?
-                    qmarksTestNocaseDot
-                    : qmarksTestNocase
-                : options.dot ? qmarksTestDot
-                    : qmarksTest)(m);
-        }
-        else if ((m = pattern.match(starDotStarRE))) {
-            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
-        }
-        else if ((m = pattern.match(dotStarRE))) {
-            fastTest = dotStarTest;
-        }
-        const re = AST.fromGlob(pattern, this.options).toMMPattern();
-        if (fastTest && typeof re === 'object') {
-            // Avoids overriding in frozen environments
-            Reflect.defineProperty(re, 'test', { value: fastTest });
-        }
-        return re;
-    }
-    makeRe() {
-        if (this.regexp || this.regexp === false)
-            return this.regexp;
-        // at this point, this.set is a 2d array of partial
-        // pattern strings, or "**".
-        //
-        // It's better to use .match().  This function shouldn't
-        // be used, really, but it's pretty convenient sometimes,
-        // when you just want to work with a regex.
-        const set = this.set;
-        if (!set.length) {
-            this.regexp = false;
-            return this.regexp;
+        const { nocase, nocaseMagicOnly, noext = false, dot, normalize, } = options;
+        const rangeMark = this.#rangeMark;
+        const lit = rangeMark && pattern.includes(rangeMark) ?
+            undefined
+            : literal(pattern, noext);
+        // in nocase mode, a literal with cased chars still needs a
+        // Matcher, unless nocaseMagicOnly is set.
+        if (lit !== undefined &&
+            !(nocase &&
+                !nocaseMagicOnly &&
+                pattern.toUpperCase() !== pattern.toLowerCase())) {
+            return this.#norm(lit);
         }
-        const options = this.options;
-        const twoStar = options.noglobstar ? star
-            : options.dot ? twoStarDot
-                : twoStarNoDot;
-        const flags = new Set(options.nocase ? ['i'] : []);
-        // regexpify non-globstar patterns
-        // if ** is only item, then we just do one twoStar
-        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
-        // if ** is last, append (\/twoStar|) to previous
-        // if ** is in the middle, append (\/|\/twoStar\/) to previous
-        // then filter out GLOBSTAR symbols
-        let re = set
-            .map(pattern => {
-            const pp = pattern.map(p => {
-                if (p instanceof RegExp) {
-                    for (const f of p.flags.split(''))
-                        flags.add(f);
-                }
-                return (typeof p === 'string' ? regExpEscape(p)
-                    : p === GLOBSTAR ? GLOBSTAR
-                        : p._src);
+        if (this.#pending)
+            return PENDING;
+        let m = this.#matchers.get(pattern);
+        if (!m) {
+            if (!noext)
+                assertValidExtglobs(pattern);
+            m = new Matcher(pattern, {
+                nocase,
+                noext,
+                dot,
+                normalize,
+                ...(rangeMark && { rangeMark }),
             });
-            pp.forEach((p, i) => {
-                const next = pp[i + 1];
-                const prev = pp[i - 1];
-                if (p !== GLOBSTAR || prev === GLOBSTAR) {
-                    return;
-                }
-                if (prev === undefined) {
-                    if (next !== undefined && next !== GLOBSTAR) {
-                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
-                    }
-                    else {
-                        pp[i] = twoStar;
-                    }
-                }
-                else if (next === undefined) {
-                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
-                }
-                else if (next !== GLOBSTAR) {
-                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
-                    pp[i + 1] = GLOBSTAR;
-                }
-            });
-            const filtered = pp.filter(p => p !== GLOBSTAR);
-            // For partial matches, we need to make the pattern match
-            // any prefix of the full path. We do this by generating
-            // alternative patterns that match progressively longer prefixes.
-            if (this.partial && filtered.length >= 1) {
-                const prefixes = [];
-                for (let i = 1; i <= filtered.length; i++) {
-                    prefixes.push(filtered.slice(0, i).join('/'));
-                }
-                return '(?:' + prefixes.join('|') + ')';
-            }
-            return filtered.join('/');
-        })
-            .join('|');
-        // need to wrap in parens if we had more than one thing with |,
-        // otherwise only the first will be anchored to ^ and the last to $
-        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
-        // must match entire pattern
-        // ending in a * or ** will make it less strict.
-        re = '^' + open + re + close + '$';
-        // In partial mode, '/' should always match as it's a valid prefix for any pattern
-        if (this.partial) {
-            re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
-        }
-        // can match anything, as long as it's not this.
-        if (this.negate)
-            re = '^(?!' + re + ').+$';
-        try {
-            this.regexp = new RegExp(re, [...flags].join(''));
-            /* c8 ignore start */
+            this.#matchers.set(pattern, m);
         }
-        catch {
-            // should be impossible
-            this.regexp = false;
-        }
-        /* c8 ignore stop */
-        return this.regexp;
+        return m;
     }
-    slashSplit(p) {
+    #slashSplit(p) {
         // if p starts with // on windows, we preserve that
         // so that UNC paths aren't broken.  Otherwise, any number of
         // / characters are coalesced into one, unless
@@ -1045,7 +1786,6 @@ export class Minimatch {
         }
     }
     match(f, partial = this.partial) {
-        this.debug('match', f, this.pattern);
         // short-circuit in the case of busted things.
         // comments, etc.
         if (this.comment) {
@@ -1058,19 +1798,36 @@ export class Minimatch {
             return true;
         }
         const options = this.options;
-        // windows: need to use /, not \
-        if (this.isWindows) {
-            f = f.split('\\').join('/');
+        // treat the test path as a set of pathparts. If it was not just
+        // split or checked, check that it can match before splitting it.
+        let split = this.#cachedSplit(f);
+        if (!split) {
+            // the checks look at the path as given, so not if it is
+            // normalized
+            if (!partial &&
+                !this.#form &&
+                (this.#endCheck || this.#literalCheck) &&
+                lastChecked !== f) {
+                lastChecked = f;
+                const can = this.#canMatch(f);
+                if (can === 'no')
+                    return options.flipNegate ? false : this.negate;
+                if (can === 'yes')
+                    return options.flipNegate ? true : !this.negate;
+            }
+            split = this.#split(f);
         }
-        // treat the test path as a set of pathparts.
-        const ff = this.slashSplit(f);
-        this.debug(this.pattern, 'split', ff);
+        const ff = split.parts;
+        // the parts after level 2 resolves them, kept for the next pattern
+        // that tests the same path
+        const resolved = this.#level2 ?
+            (split.resolved ??= this.#levelTwoFileOptimize(ff))
+            : ff;
         // just ONE of the pattern sets in this.set needs to match
         // in order for it to be valid.  If negating, then just one
         // match means that we have failed.
         // Either way, return on the first hit.
         const set = this.set;
-        this.debug(this.pattern, 'set', set);
         // Find the basename of the path by looking for the last non-empty segment
         let filename = ff[ff.length - 1];
         if (!filename) {
@@ -1078,12 +1835,16 @@ export class Minimatch {
                 filename = ff[i];
             }
         }
-        for (const pattern of set) {
-            let file = ff;
-            if (options.matchBase && pattern.length === 1) {
-                file = [filename];
-            }
-            const hit = this.matchOne(file, pattern, partial);
+        for (let r = 0; r < set.length; r++) {
+            const pattern = set[r];
+            const shape = partial ? undefined : this.#shapes[r];
+            // level 2 does not change a path of one portion
+            const hit = shape === 'base' ?
+                portionMatch(pattern[0], filename)
+                : shape ? this.#matchShape(resolved, pattern, shape)
+                    : options.matchBase && pattern.length === 1 ?
+                        this.#matchRow([filename], [filename], pattern, partial)
+                        : this.#matchRow(ff, resolved, pattern, partial);
             if (hit) {
                 if (options.flipNegate) {
                     return true;
@@ -1103,11 +1864,9 @@ export class Minimatch {
     }
 }
 /* c8 ignore start */
-export { AST } from './ast.js';
 export { escape } from './escape.js';
 export { unescape } from './unescape.js';
 /* c8 ignore stop */
-minimatch.AST = AST;
 minimatch.Minimatch = Minimatch;
 minimatch.escape = escape;
 minimatch.unescape = unescape;
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.js.map
index 431b3a15a00c29459ae73326910924b895e61885..ca75baab61d24b50a562ec5e6fc813a820da014b 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.js.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/index.js.map
@@ -1 +1 @@
-{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAE9D,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAqHxC,MAAM,CAAC,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,UAA4B,EAAE,EAC9B,EAAE;IACF,kBAAkB,CAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QACpD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC,CAAA;AAED,wDAAwD;AACxD,MAAM,YAAY,GAAG,oBAAoB,CAAA;AACzC,MAAM,cAAc,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,CAAS,EAAE,EAAE,CACpD,CAAC,CAAC,CAAC,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AC,IAAI,CAAC,MAAM,CAAA;YACrB,CAAC;QACH,CAAC;QAED,2DAA2D;QAC3D,8BAA8B;QAC9B,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AACD,qBAAqB;AACrB,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AACxC,oBAAoB;AACpB,SAAS,CAAC,GAAG,GAAG,GAAG,CAAA;AACnB,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;AAC/B,SAAS,CAAC,MAAM,GAAG,MAAM,CAAA;AACzB,SAAS,CAAC,QAAQ,GAAG,QAAQ,CAAA","sourcesContent":["import { expand } from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport type { ExtglobType } from './ast.js'\nimport { AST } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\nexport type Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  /** do not expand `{x,y}` style braces */\n  nobrace?: boolean\n  /** do not treat patterns starting with `#` as a comment */\n  nocomment?: boolean\n  /** do not treat patterns starting with `!` as a negation */\n  nonegate?: boolean\n  /** print LOTS of debugging output */\n  debug?: boolean\n  /** treat `**` the same as `*` */\n  noglobstar?: boolean\n  /** do not expand extglobs like `+(a|b)` */\n  noext?: boolean\n  /** return the pattern if nothing matches */\n  nonull?: boolean\n  /** treat `\\\\` as a path separator, not an escape character */\n  windowsPathsNoEscape?: boolean\n  /**\n   * inverse of {@link MinimatchOptions.windowsPathsNoEscape}\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n  /**\n   * Compare a partial path to a pattern. As long as the parts\n   * of the path that are present are not contradicted by the\n   * pattern, it will be treated as a match. This is useful in\n   * applications where you're walking through a folder structure,\n   * and don't yet have the full path, but want to ensure that you\n   * do not walk down paths that can never be a match.\n   */\n  partial?: boolean\n  /** allow matches that start with `.` even if the pattern does not */\n  dot?: boolean\n  /** ignore case */\n  nocase?: boolean\n  /** ignore case only in wildcard patterns */\n  nocaseMagicOnly?: boolean\n  /** consider braces to be \"magic\" for the purpose of `hasMagic` */\n  magicalBraces?: boolean\n  /**\n   * If set, then patterns without slashes will be matched\n   * against the basename of the path if it contains slashes.\n   * For example, `a?b` would match the path `/xyz/123/acb`, but\n   * not `/xyz/acb/123`.\n   */\n  matchBase?: boolean\n  /** invert the results of negated matches */\n  flipNegate?: boolean\n  /** do not collapse multiple `/` into a single `/` */\n  preserveMultipleSlashes?: boolean\n  /**\n   * A number indicating the level of optimization that should be done\n   * to the pattern prior to parsing and using it for matches.\n   */\n  optimizationLevel?: number\n  /** operating system platform */\n  platform?: Platform\n  /**\n   * When a pattern starts with a UNC path or drive letter, and in\n   * `nocase:true` mode, do not convert the root portions of the\n   * pattern into a case-insensitive regular expression, and instead\n   * leave them as strings.\n   *\n   * This is the default when the platform is `win32` and\n   * `nocase:true` is set.\n   */\n  windowsNoMagicRoot?: boolean\n  /**\n   * max number of `{...}` patterns to expand. Default 100_000.\n   */\n  braceExpandMax?: number\n  /**\n   * Max number of non-adjacent `**` patterns to recursively walk down.\n   *\n   * The default of 200 is almost certainly high enough for most purposes,\n   * and can handle absurdly excessive patterns.\n   */\n  maxGlobstarRecursion?: number\n\n  /**\n   * Max depth to traverse for nested extglobs like `*(a|b|c)`\n   *\n   * Default is 2, which is quite low, but any higher value\n   * swiftly results in punishing performance impacts. Note\n   * that this is *not*  relevant when the globstar types can\n   * be safely coalesced into a single set.\n   *\n   * For example, `*(a|@(b|c)|d)` would be flattened into\n   * `*(a|b|c|d)`. Thus, many common extglobs will retain good\n   * performance and  never hit this limit, even if they are\n   * excessively deep and complicated.\n   *\n   * If the limit is hit, then the extglob characters are simply\n   * not parsed, and the pattern effectively switches into\n   * `noextglob: true` mode for the contents of that nested\n   * sub-pattern. This will typically _not_ result in a match,\n   * but is considered a valid trade-off for security and\n   * performance.\n   */\n  maxExtglobRecursion?: number\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?*[(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n  !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n  ext = ext.toLowerCase()\n  return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) =>\n  !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n  f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) =>\n  f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) =>\n  f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?*[(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  if (!ext) return noext\n  ext = ext.toLowerCase()\n  return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExtDot([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n  const noext = qmarksTestNoExt([$0])\n  return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n  const len = $0.length\n  return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process ?\n    (typeof process.env === 'object' &&\n      process.env &&\n      process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n    process.platform\n  : 'posix') as Platform\n\nexport type Sep = '\\\\' | '/'\n\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep =\n  defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed.  Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n  (pattern: string, options: MinimatchOptions = {}) =>\n  (p: string) =>\n    minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    AST: class AST extends orig.AST {\n      /* c8 ignore start */\n      constructor(\n        type: ExtglobType | null,\n        parent?: AST,\n        options: MinimatchOptions = {},\n      ) {\n        super(type, parent, ext(def, options))\n      }\n      /* c8 ignore stop */\n\n      static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n        return orig.AST.fromGlob(pattern, ext(def, options))\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) =>\n      orig.defaults(ext(def, options)),\n\n    makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.makeRe(pattern, ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (\n      list: string[],\n      pattern: string,\n      options: MinimatchOptions = {},\n    ) => orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  return expand(pattern, { max: options.braceExpandMax })\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion.  Otherwise, any series\n// of * is equivalent to a single *.  Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n  new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n  list: string[],\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n  _src?: string\n  _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n  maxGlobstarRecursion: number\n\n  regexp: false | null | MMRegExp\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    // avoid the annoying deprecation flag lol\n    const awe = ('allowWindow' + 'sEscape') as keyof MinimatchOptions\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options[awe] === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.regexp = null\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined ?\n        options.windowsNoMagicRoot\n      : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n\n    // make the set of regexps etc.\n    this.make()\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  debug(..._: unknown[]) {}\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.braceExpand())]\n\n    if (options.debug) {\n      //oxlint-disable-next-line no-console\n      this.debug = (...args: unknown[]) => console.error(...args)\n    }\n\n    this.debug(this.pattern, this.globSet)\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be regexps, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n    this.debug(this.pattern, this.globParts)\n\n    // glob --> regexps\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path.\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          !globMagic.test(s[3])\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [\n            ...s.slice(0, 4),\n            ...s.slice(4).map(ss => this.parse(ss)),\n          ]\n        } else if (isDrive) {\n          return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    this.debug(this.pattern, set)\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1,\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          typeof p[3] === 'string' &&\n          /^[a-z]:$/i.test(p[3])\n        ) {\n          p[2] = '?'\n        }\n      }\n    }\n\n    this.debug(this.pattern, this.set)\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn ** into *\n    if (this.options.noglobstar) {\n      for (const partset of globParts) {\n        for (let j = 0; j < partset.length; j++) {\n          if (partset[j] === '**') {\n            partset[j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  levelTwoFileOptimize(parts: string | string[]) {\n    if (!Array.isArray(parts)) {\n      parts = this.slashSplit(parts)\n    }\n    let didSomething: boolean = false\n\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (\n          p &&\n          p !== '.' &&\n          p !== '..' &&\n          p !== '**' &&\n          !(this.isWindows && /^[a-z]:$/i.test(p))\n        ) {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes,\n        )\n        if (matched) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false,\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean = false,\n  ) {\n    let fileStartIndex = 0\n    let patternStartIndex = 0\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi =\n        fileUNC ? 3\n        : fileDrive ? 0\n        : undefined\n      const pdi =\n        patternUNC ? 3\n        : patternDrive ? 0\n        : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        // start matching at the drive letter index of each\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          patternStartIndex = pdi\n          fileStartIndex = fdi\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // don't need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    if (pattern.includes(GLOBSTAR)) {\n      return this.#matchGlobstar(\n        file,\n        pattern,\n        partial,\n        fileStartIndex,\n        patternStartIndex,\n      )\n    }\n\n    return this.#matchOne(\n      file,\n      pattern,\n      partial,\n      fileStartIndex,\n      patternStartIndex,\n    )\n  }\n\n  #matchGlobstar(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n  ) {\n    // split the pattern into head, tail, and middle of ** delimited parts\n    const firstgs = pattern.indexOf(GLOBSTAR, patternIndex)\n    const lastgs = pattern.lastIndexOf(GLOBSTAR)\n\n    // split the pattern up into globstar-delimited sections\n    // the tail has to be at the end, and the others just have\n    // to be found in order from the head.\n    const [head, body, tail] =\n      partial ?\n        [\n          pattern.slice(patternIndex, firstgs),\n          pattern.slice(firstgs + 1),\n          [],\n        ]\n      : [\n          pattern.slice(patternIndex, firstgs),\n          pattern.slice(firstgs + 1, lastgs),\n          pattern.slice(lastgs + 1),\n        ]\n\n    // check the head, from the current file/pattern index.\n    if (head.length) {\n      const fileHead = file.slice(fileIndex, fileIndex + head.length)\n      if (!this.#matchOne(fileHead, head, partial, 0, 0)) {\n        return false\n      }\n      fileIndex += head.length\n      patternIndex += head.length\n    }\n    // now we know the head matches!\n\n    // if the last portion is not empty, it MUST match the end\n    // check the tail\n    let fileTailMatch: number = 0\n    if (tail.length) {\n      // if head + tail > file, then we cannot possibly match\n      if (tail.length + fileIndex > file.length) return false\n\n      // try to match the tail\n      let tailStart = file.length - tail.length\n      if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n        fileTailMatch = tail.length\n      } else {\n        // affordance for stuff like a/**/* matching a/b/\n        // if the last file portion is '', and there's more to the pattern\n        // then try without the '' bit.\n        if (\n          file[file.length - 1] !== '' ||\n          fileIndex + tail.length === file.length\n        ) {\n          return false\n        }\n        tailStart--\n        if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n          return false\n        }\n        fileTailMatch = tail.length + 1\n      }\n    }\n\n    // now we know the tail matches!\n\n    // the middle is zero or more portions wrapped in **, possibly\n    // containing more ** sections.\n    // so a/**/b/**/c/**/d has become **/b/**/c/**\n    // if it's empty, it means a/**/b, just verify we have no bad dots\n    // if there's no tail, so it ends on /**, then we must have *something*\n    // after the head, or it's not a matc\n    if (!body.length) {\n      let sawSome = !!fileTailMatch\n      for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n        const f = String(file[i])\n        sawSome = true\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      // in partial mode, we just need to get past all file parts\n      return partial || sawSome\n    }\n\n    // now we know that there's one or more body sections, which can\n    // be matched anywhere from the 0 index (because the head was pruned)\n    // through to the length-fileTailMatch index.\n    // split the body up into sections, and note the minimum index it can\n    // be found at (start with the length of all previous segments)\n    // [section, before, after]\n    const bodySegments: [ParseReturn[], number][] = [[[], 0]]\n    let currentBody: [ParseReturn[], number] = bodySegments[0]\n    let nonGsParts = 0\n    const nonGsPartsSums: number[] = [0]\n    for (const b of body) {\n      if (b === GLOBSTAR) {\n        nonGsPartsSums.push(nonGsParts)\n        currentBody = [[], 0]\n        bodySegments.push(currentBody)\n      } else {\n        currentBody[0].push(b)\n        nonGsParts++\n      }\n    }\n    let i = bodySegments.length - 1\n    const fileLength = file.length - fileTailMatch\n    for (const b of bodySegments) {\n      b[1] = fileLength - ((nonGsPartsSums[i--] as number) + b[0].length)\n    }\n\n    return !!this.#matchGlobStarBodySections(\n      file,\n      bodySegments,\n      fileIndex,\n      0,\n      partial,\n      0,\n      !!fileTailMatch,\n    )\n  }\n\n  // return false for \"nope, not matching\"\n  // return null for \"not matching, cannot keep trying\"\n  #matchGlobStarBodySections(\n    file: string[],\n    // pattern section, last possible position for it\n    bodySegments: [ParseReturn[], number][],\n    fileIndex: number,\n    bodyIndex: number,\n    partial: boolean,\n    globStarDepth: number,\n    sawTail: boolean,\n  ): boolean | null {\n    // take the first body segment, and walk from fileIndex to its \"after\"\n    // value at the end\n    // If it doesn't match at that position, we increment, until we hit\n    // that final possible position, and give up.\n    // If it does match, then advance and try to rest.\n    // If any of them fail we keep walking forward.\n    // this is still a bit recursively painful, but it's more constrained\n    // than previous implementations, because we never test something that\n    // can't possibly be a valid matching condition.\n    const bs = bodySegments[bodyIndex]\n    if (!bs) {\n      // just make sure that there's no bad dots\n      for (let i = fileIndex; i < file.length; i++) {\n        sawTail = true\n        const f = file[i]\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      return sawTail\n    }\n\n    // have a non-globstar body section to test\n    const [body, after] = bs\n    while (fileIndex <= after) {\n      const m = this.#matchOne(\n        file.slice(0, fileIndex + body.length),\n        body,\n        partial,\n        fileIndex,\n        0,\n      )\n      // if limit exceeded, no match. intentional false negative,\n      // acceptable break in correctness for security.\n      if (m && globStarDepth < this.maxGlobstarRecursion) {\n        // match! see if the rest match. if so, we're done!\n        const sub = this.#matchGlobStarBodySections(\n          file,\n          bodySegments,\n          fileIndex + body.length,\n          bodyIndex + 1,\n          partial,\n          globStarDepth + 1,\n          sawTail,\n        )\n        if (sub !== false) {\n          return sub\n        }\n      }\n      const f = file[fileIndex]\n      if (\n        f === '.' ||\n        f === '..' ||\n        (!this.options.dot && f.startsWith('.'))\n      ) {\n        return false\n      }\n\n      fileIndex++\n    }\n    // walked off. no point continuing\n    return partial || null\n  }\n\n  #matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n  ) {\n    let fi: number\n    let pi: number\n    let pl: number\n    let fl: number\n    for (\n      fi = fileIndex,\n        pi = patternIndex,\n        fl = file.length,\n        pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      let p = pattern[pi]\n      let f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      // should be impossible.\n      // some invalid regexp stuff in the set.\n      /* c8 ignore start */\n      if (p === false || p === GLOBSTAR) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into regexps.\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though \"\" matches against the\n    // [^/]*? pattern, except in partial mode, where it might\n    // simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase ?\n          options.dot ?\n            starDotExtTestNocaseDot\n          : starDotExtTestNocase\n        : options.dot ? starDotExtTestDot\n        : starDotExtTest)(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase ?\n          options.dot ?\n            qmarksTestNocaseDot\n          : qmarksTestNocase\n        : options.dot ? qmarksTestDot\n        : qmarksTest)(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar =\n      options.noglobstar ? star\n      : options.dot ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return (\n            typeof p === 'string' ? regExpEscape(p)\n            : p === GLOBSTAR ? GLOBSTAR\n            : p._src\n          )\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        const filtered = pp.filter(p => p !== GLOBSTAR)\n\n        // For partial matches, we need to make the pattern match\n        // any prefix of the full path. We do this by generating\n        // alternative patterns that match progressively longer prefixes.\n        if (this.partial && filtered.length >= 1) {\n          const prefixes: string[] = []\n          for (let i = 1; i <= filtered.length; i++) {\n            prefixes.push(filtered.slice(0, i).join('/'))\n          }\n          return '(?:' + prefixes.join('|') + ')'\n        }\n\n        return filtered.join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // In partial mode, '/' should always match as it's a valid prefix for any pattern\n    if (this.partial) {\n      re = '^(?:\\\\/|' + open + re.slice(1, -1) + close + ')$'\n    }\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (const pattern of set) {\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n"]}
\ No newline at end of file
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MA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A8B;QAC9B,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AACD,qBAAqB;AACrB,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,oBAAoB;AACpB,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;AAC/B,SAAS,CAAC,MAAM,GAAG,MAAM,CAAA;AACzB,SAAS,CAAC,QAAQ,GAAG,QAAQ,CAAA","sourcesContent":["import { expand } from 'brace-expansion'\nimport { Matcher, type Form } from '@isaacs/nonrecursive-glob-match'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\nconst DEFAULT_BRACE_EXPAND_MAX = 100_000\nconst DEFAULT_GLOB_STAR_RECURSION_MAX = 200\n// avoid the annoying deprecation flag lol\nconst AWE_KEY = ('allowWindow' + 'sEscape') as keyof MinimatchOptions\n\nexport type Platform =\n  | 'aix'\n  | 'android'\n  | 'darwin'\n  | 'freebsd'\n  | 'haiku'\n  | 'linux'\n  | 'openbsd'\n  | 'sunos'\n  | 'win32'\n  | 'cygwin'\n  | 'netbsd'\n\nexport interface MinimatchOptions {\n  /** do not expand `{x,y}` style braces */\n  nobrace?: boolean\n  /** do not treat patterns starting with `#` as a comment */\n  nocomment?: boolean\n  /** do not treat patterns starting with `!` as a negation */\n  nonegate?: boolean\n  /** treat `**` the same as `*` */\n  noglobstar?: boolean\n  /** do not expand extglobs like `+(a|b)` */\n  noext?: boolean\n  /** return the pattern if nothing matches */\n  nonull?: boolean\n  /** treat `\\\\` as a path separator, not an escape character */\n  windowsPathsNoEscape?: boolean\n  /**\n   * inverse of {@link MinimatchOptions.windowsPathsNoEscape}\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n  /**\n   * Compare a partial path to a pattern. As long as the parts\n   * of the path that are present are not contradicted by the\n   * pattern, it will be treated as a match. This is useful in\n   * applications where you're walking through a folder structure,\n   * and don't yet have the full path, but want to ensure that you\n   * do not walk down paths that can never be a match.\n   */\n  partial?: boolean\n  /** allow matches that start with `.` even if the pattern does not */\n  dot?: boolean\n  /** ignore case */\n  nocase?: boolean\n  /** ignore case only in wildcard patterns */\n  nocaseMagicOnly?: boolean\n  /**\n   * Normalize unicode in the pattern and in each portion of the\n   * tested paths, with this form. `true` means `'NFC'`.\n   */\n  normalize?: boolean | Form\n  /** consider braces to be \"magic\" for the purpose of `hasMagic` */\n  magicalBraces?: boolean\n  /**\n   * If set, then patterns without slashes will be matched\n   * against the basename of the path if it contains slashes.\n   * For example, `a?b` would match the path `/xyz/123/acb`, but\n   * not `/xyz/acb/123`.\n   */\n  matchBase?: boolean\n  /** invert the results of negated matches */\n  flipNegate?: boolean\n  /** do not collapse multiple `/` into a single `/` */\n  preserveMultipleSlashes?: boolean\n  /**\n   * A number indicating the level of optimization that should be done\n   * to the pattern prior to parsing and using it for matches.\n   * At level 2 or higher, throws RangeError if splitting `**` and `..`\n   * would make more than `braceExpandMax` patterns, or add more than\n   * 1,000,000 path portions.\n   */\n  optimizationLevel?: number\n  /** operating system platform */\n  platform?: Platform\n  /**\n   * When a pattern starts with a UNC path or drive letter, and in\n   * `nocase:true` mode, do not convert the root portions of the\n   * pattern into a case-insensitive regular expression, and instead\n   * leave them as strings.\n   *\n   * This is the default when the platform is `win32` and\n   * `nocase:true` is set.\n   */\n  windowsNoMagicRoot?: boolean\n  /**\n   * max number of `{...}` patterns to expand. Default 100_000.\n   *\n   * At `optimizationLevel` 2 or higher, this also limits the\n   * patterns made when `**` is followed by `..`. Over this limit,\n   * construction throws a RangeError.\n   */\n  braceExpandMax?: number\n  /**\n   * Max number of non-adjacent `**` patterns to recursively walk down.\n   *\n   * The default of 200 is almost certainly high enough for most purposes,\n   * and can handle absurdly excessive patterns.\n   */\n  maxGlobstarRecursion?: number\n}\n\nexport const minimatch = (\n  p: string,\n  pattern: string,\n  options?: MinimatchOptions,\n) => {\n  assertValidPattern(pattern)\n\n  // shortcut: comments match nothing.\n  if (!options?.nocomment && pattern.charAt(0) === '#') {\n    return false\n  }\n\n  return cachedMinimatch(pattern, options).match(p)\n}\n\n// The Minimatch objects that minimatch() used most recently, by options\n// and then by pattern. When the cache is full, it becomes the old one,\n// and the objects used from the old one are moved back to a new one.\n// So it keeps 256 to 512 objects.\n// The patterns can come from users, so the cache is also bounded by\n// the total weight of the objects (see cacheWeight()), and an object\n// that is too heavy is never kept. Otherwise a few unique patterns\n// with large brace expansions would fill the heap.\nlet cache = new Map>()\nlet oldCache = new Map>()\nlet cacheSize = 0\nlet cacheTotalWeight = 0\nconst cacheMax = 256\nconst cacheMaxWeight = 1 << 15\nconst cacheMaxEntryWeight = 1 << 12\n\n// About the memory that a compiled object keeps: the pattern and the\n// expanded patterns, of which each row in set is made.\nconst cacheWeight = (mm: Minimatch): number => {\n  let w = mm.pattern.length\n  for (const s of mm.globSet) {\n    w += s.length + 1\n    if (w > cacheMaxEntryWeight) break\n  }\n  return w\n}\n\ntype BooleanOption =\n  | 'nobrace'\n  | 'nocomment'\n  | 'nonegate'\n  | 'noglobstar'\n  | 'noext'\n  | 'nonull'\n  | 'windowsPathsNoEscape'\n  | 'allowWindowsEscape'\n  | 'partial'\n  | 'dot'\n  | 'nocase'\n  | 'nocaseMagicOnly'\n  | 'magicalBraces'\n  | 'matchBase'\n  | 'flipNegate'\n  | 'preserveMultipleSlashes'\n  | 'windowsNoMagicRoot'\ntype OtherOption =\n  | 'normalize'\n  | 'platform'\n  | 'optimizationLevel'\n  | 'braceExpandMax'\n  | 'maxGlobstarRecursion'\n// tsc fails here if a new option is in neither type. Add it to\n// optionsKey() too.\nconst allOptionsKeyed: [\n  Exclude,\n] extends [never] ?\n  true\n: never = true\nvoid allOptionsKeyed\n\n// 0, 1 or 2 for undefined, falsy or truthy.\nconst tri = (v: unknown) =>\n  v === undefined ? 0\n  : v ? 2\n  : 1\n\n// The weight of each boolean option's base-3 digit in the key. The\n// weights below 24 are for optimizationLevel (1), platform (3) and\n// windowsPathsNoEscape (12). tsc fails here if a boolean option is\n// not in the list.\nconst booleanWeights = new Map(\n  Object.keys({\n    nobrace: 0,\n    nocomment: 0,\n    nonegate: 0,\n    noglobstar: 0,\n    noext: 0,\n    nonull: 0,\n    partial: 0,\n    dot: 0,\n    nocase: 0,\n    nocaseMagicOnly: 0,\n    magicalBraces: 0,\n    matchBase: 0,\n    flipNegate: 0,\n    preserveMultipleSlashes: 0,\n    windowsNoMagicRoot: 0,\n  } satisfies Record<\n    Exclude,\n    0\n  >).map((k, i) => [k, 24 * 3 ** i]),\n)\n\n// The cache key for a set of options. It is a number, unless an\n// option is set to a value that the number can not show, such as\n// normalize or an uncommon platform. Then it is a JSON string.\n// The defaults give 0, the same key as no options.\n// It only reads the keys that are set, so that the speed does not\n// depend on the shape of the options object.\nconst optionsKey = (o: MinimatchOptions): number | string => {\n  let n = 0\n  let wpe = false\n  // inherited keys too, because Minimatch reads them\n  // oxlint-disable-next-line guard-for-in\n  for (const k in o) {\n    const v = (o as Record)[k]\n    switch (k) {\n      // the same test as the Minimatch constructor\n      case 'windowsPathsNoEscape':\n        if (v) wpe = true\n        break\n      case AWE_KEY:\n        if (v === false) wpe = true\n        break\n\n      case 'platform': {\n        // the same test as the Minimatch constructor\n        const p = v || defaultPlatform\n        if (p === defaultPlatform) break\n        if (p === 'darwin') n += 3\n        else if (p === 'win32') n += 6\n        else if (p === 'linux') n += 9\n        else return JSON.stringify(o)\n        break\n      }\n\n      case 'optimizationLevel':\n        // The same tests as Minimatch: 1 when undefined, then >= 2,\n        // >= 1, or else 0. The default level 1 adds 0.\n        if (v === undefined) break\n        n +=\n          (v as number) >= 2 ? 1\n          : (v as number) >= 1 ? 0\n          : 2\n        break\n\n      case 'braceExpandMax':\n        if (v !== undefined && v !== DEFAULT_BRACE_EXPAND_MAX) {\n          return JSON.stringify(o)\n        }\n        break\n      case 'maxGlobstarRecursion':\n        if (v !== undefined && v !== DEFAULT_GLOB_STAR_RECURSION_MAX) {\n          return JSON.stringify(o)\n        }\n        break\n      case 'normalize':\n        if (v !== undefined) return JSON.stringify(o)\n        break\n\n      default:\n        // unknown keys have no weight\n        n += (booleanWeights.get(k) ?? 0) * tri(v)\n    }\n  }\n  return wpe ? n + 12 : n\n}\n\n// A copy, so a later change to the options can not change it. Unlike\n// a spread, it keeps the inherited keys, which optionsKey() and the\n// Minimatch constructor also read.\nconst copyOptions = (o?: MinimatchOptions) => {\n  const copy: Record = {}\n  // oxlint-disable-next-line guard-for-in\n  for (const k in o) copy[k] = (o as Record)[k]\n  return copy as MinimatchOptions\n}\n\nconst cachedMinimatch = (pattern: string, options?: MinimatchOptions) => {\n  const key = options ? optionsKey(options) : 0\n  let mm = cache.get(key)?.get(pattern)\n  if (mm) return mm\n  mm =\n    oldCache.get(key)?.get(pattern) ??\n    new Minimatch(pattern, copyOptions(options))\n  const weight = cacheWeight(mm)\n  // too big to keep, so it is compiled again each time\n  if (weight > cacheMaxEntryWeight) return mm\n  if (\n    cacheSize >= cacheMax ||\n    cacheTotalWeight + weight > cacheMaxWeight\n  ) {\n    oldCache = cache\n    cache = new Map()\n    cacheSize = 0\n    cacheTotalWeight = 0\n  }\n  let byPattern = cache.get(key)\n  if (!byPattern) cache.set(key, (byPattern = new Map()))\n  byPattern.set(pattern, mm)\n  cacheSize++\n  cacheTotalWeight += weight\n  return mm\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n  typeof process === 'object' && process ?\n    process.env?.__MINIMATCH_TESTING_PLATFORM__ || process.platform\n  : 'posix') as Platform\n\nexport type Sep = '\\\\' | '/'\n\nconst path: { [k: string]: { sep: Sep } } = {\n  win32: { sep: '\\\\' },\n  posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep =\n  defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\nexport const filter = (pattern: string, options?: MinimatchOptions) => {\n  let mm: Minimatch | undefined\n  return (p: string) => (mm ??= cachedMinimatch(pattern, options)).match(p)\n}\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n  Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n  if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n    return minimatch\n  }\n\n  const orig = minimatch\n\n  const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n    orig(p, pattern, ext(def, options))\n\n  return Object.assign(m, {\n    Minimatch: class Minimatch extends orig.Minimatch {\n      constructor(pattern: string, options: MinimatchOptions = {}) {\n        super(pattern, ext(def, options))\n      }\n      static defaults(options: MinimatchOptions) {\n        return orig.defaults(ext(def, options)).Minimatch\n      }\n    },\n\n    unescape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.unescape(s, ext(def, options)),\n\n    escape: (\n      s: string,\n      options: Pick<\n        MinimatchOptions,\n        'windowsPathsNoEscape' | 'magicalBraces'\n      > = {},\n    ) => orig.escape(s, ext(def, options)),\n\n    filter: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.filter(pattern, ext(def, options)),\n\n    defaults: (options: MinimatchOptions) =>\n      orig.defaults(ext(def, options)),\n\n    braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n      orig.braceExpand(pattern, ext(def, options)),\n\n    match: (\n      list: string[],\n      pattern: string,\n      options: MinimatchOptions = {},\n    ) => orig.match(list, pattern, ext(def, options)),\n\n    sep: orig.sep,\n    GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n  })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  assertValidPattern(pattern)\n\n  // Thanks to Yeting Li  for\n  // improving this regexp to avoid a ReDOS vulnerability.\n  if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n    // shortcut. no need to expand.\n    return [pattern]\n  }\n\n  // brace-expansion turns each escaped backslash '\\\\' into a single '\\',\n  // which then escapes the next character instead, and can turn an\n  // escaped magic character (for example '\\\\\\*') into a live one.\n  // Double every pair, so an escaped backslash comes back out still\n  // escaped. The parity of each run of backslashes is unchanged.\n  let p = pattern.replace(/\\\\\\\\/g, '\\\\\\\\\\\\\\\\')\n  // brace-expansion does not know about [...] classes. In\n  // windowsPathsNoEscape mode, escape() writes a literal brace as '[{]'\n  // or '[}]'. Escape the brace for brace-expansion, which removes that\n  // backslash again, leaving '[{]' or '[}]'.\n  if (options.windowsPathsNoEscape || options[AWE_KEY] === false) {\n    p = p.replace(/\\[([{}])\\]/g, '[\\\\$1]')\n  }\n  return expand(p, { max: options.braceExpandMax })\n}\nminimatch.braceExpand = braceExpand\n\n// A numeric range with at least this many values is matched as one\n// pattern portion, rather than expanded. For a glob walk, that is\n// one directory read, in place of a stat for each value.\nconst RANGE_MIN = 100\n// a {lo..hi} range that is not escaped, and not a ${...} variable\nconst rangeRe = /(? {\n  const stack: string[] = []\n  for (let i = 0; i < portion.length; i++) {\n    const c = portion.charAt(i)\n    if (c === '\\\\') {\n      i++\n    } else if (c === mark) {\n      if (stack.some(t => t !== '@' && t !== '?')) return true\n    } else if (portion.charAt(i + 1) === '(' && '!?+*@'.includes(c)) {\n      stack.push(c)\n      i++\n    } else if (c === ')') {\n      stack.pop()\n    }\n  }\n  return false\n}\n\nexport const match = (\n  list: string[],\n  pattern: string,\n  options: MinimatchOptions = {},\n) => {\n  const mm = new Minimatch(pattern, options)\n  list = list.filter(f => mm.match(f))\n  if (mm.options.nonull && !list.length) {\n    list.push(pattern)\n  }\n  return list\n}\nminimatch.match = match\n\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\n\n// Index of the `]` that closes the class that starts at `start`,\n// or -1 if it is not closed. Posix classes such as `[:alpha:]` are\n// not skipped, so this can find a `]` before the real end. That\n// only makes a class look less like a literal.\nconst classEnd = (pattern: string, start: number) => {\n  let i = start + 1\n  if (pattern.charAt(i) === '!' || pattern.charAt(i) === '^') i++\n  let sawStart = false\n  for (; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === ']' && sawStart) return i\n    sawStart = true\n    if (c === '\\\\') i++\n  }\n  return -1\n}\n\n// If a path portion pattern has no magic, return the string it\n// matches. Otherwise, return undefined. This can report magic for\n// a pattern that is in fact literal (eg, `[]`), but never the\n// reverse, so a string result is always safe to compare directly.\nconst literal = (pattern: string, noext: boolean): string | undefined => {\n  if (!noext && (pattern === '+()' || pattern === '@()')) return pattern\n  let lit = ''\n  for (let i = 0; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      // a trailing \\ is a literal \\\n      lit += pattern.charAt(++i) || c\n    } else if (c === '*' || c === '?') {\n      return undefined\n    } else if (c === '[') {\n      const close = classEnd(pattern, i)\n      if (close === -1) {\n        // not closed, so the [ is a literal\n        lit += c\n        continue\n      }\n      // a class of one char, such as `[*]` or `[\\b]`, is a literal\n      let body = pattern.slice(i + 1, close)\n      if (body.startsWith('\\\\')) body = body.slice(1)\n      if ([...body].length !== 1 || '!^'.includes(pattern.charAt(i + 1))) {\n        return undefined\n      }\n      lit += body\n      i = close\n    } else if (\n      !noext &&\n      '+@!'.includes(c) &&\n      pattern.charAt(i + 1) === '(' &&\n      pattern.includes(')', i + 2)\n    ) {\n      return undefined\n    } else {\n      lit += c\n    }\n  }\n  return lit\n}\n\n// The matching engine compiles and walks extglobs recursively, so a\n// path portion with very many extglobs (nested, such as `*(*(*(a)))`,\n// or in a row, such as `?(a)?(a)?(a)`) can exhaust the call stack.\n// Portions with more than this many extglobs are rejected.\nconst MAX_EXTGLOBS = 256\n\n// The number of extglob openers, such as `*(`, in a path portion\n// pattern. Chars in a class are counted too, so this can be more than\n// the number of extglobs, but never less.\nconst extglobCount = (pattern: string): number => {\n  let n = 0\n  for (let i = 0; i < pattern.length - 1; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      i++\n    } else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') {\n      n++\n      i++\n    }\n  }\n  return n\n}\n\nconst assertValidExtglobs = (pattern: string) => {\n  if (extglobCount(pattern) > MAX_EXTGLOBS) {\n    throw new TypeError('pattern has too many extglobs')\n  }\n}\n\n// True if the portion pattern has the same meaning as an alternative\n// inside `@(...)`. It must not have a `|` or `)` that is not in a\n// closed extglob (those are literal at the top level), an extglob\n// that is not closed (the `)` of the `@(...)` would close it), or a\n// trailing `\\` (it would escape the next `|`). A pattern that is\n// only an empty extglob, such as `?()`, is literal on its own, but\n// not in `@(...)`. Posix classes such as `[:alpha:]` can hide a `]`\n// from classEnd, so patterns with them are not merged.\nconst extSafe = (pattern: string) => {\n  if (/^[?*+@]\\(\\)$/.test(pattern) || pattern.includes('[:')) return false\n  let depth = 0\n  for (let i = 0; i < pattern.length; i++) {\n    const c = pattern.charAt(i)\n    if (c === '\\\\') {\n      if (++i === pattern.length) return false\n    } else if (c === '[') {\n      const close = classEnd(pattern, i)\n      if (close !== -1) i = close\n    } else if ('+@!?*'.includes(c) && pattern.charAt(i + 1) === '(') {\n      depth++\n      i++\n    } else if (c === ')') {\n      if (!depth--) return false\n    } else if (c === '|' && !depth) {\n      return false\n    }\n  }\n  return !depth\n}\n\n// The last path that Minimatch#match split, and its parts. A path is\n// often tested against many patterns in a row (such as a list of\n// ignore patterns), so this saves splitting it again. The parts are\n// never changed, so they can be shared.\nlet lastSplit: SplitPath | undefined\n\n/**\n * A path that Minimatch#match split, with the settings that the split\n * depends on. `resolved` is the parts after optimizationLevel 2 has\n * resolved `.` and `..` in them, which only depends on the same\n * settings, once a level 2 Minimatch has needed them.\n */\nexport type SplitPath = {\n  f: string\n  isWindows: boolean\n  preserveMultipleSlashes: boolean\n  normalize: Form | undefined\n  parts: string[]\n  resolved?: string[]\n}\n\n// The last path that Minimatch#match checked before splitting it. If\n// the same path is checked again, it is being tested against many\n// patterns, so it is split and the parts are kept for the others.\nlet lastChecked: string | undefined\n\nexport type ParseReturnFiltered = string | Matcher | typeof GLOBSTAR\n\n/**\n * The rows that Minimatch#match can match without splitting the path:\n * `**` and one more portion (`tail`), a portion with `**` on each side\n * of it (`mid`), a portion and then `**` (`head`), or one portion that\n * matches the basename of the path, with matchBase (`base`).\n */\nexport type RowShape = 'tail' | 'mid' | 'head' | 'base'\n\n// true if a pattern portion that is not ** matches a path portion.\n// An empty path portion only matches an empty pattern portion. A path\n// portion never has a `/`, so the Matcher does not need to check it.\nconst portionMatch = (p: string | Matcher, f: string) =>\n  typeof p === 'string' ? f === p : f !== '' && p.testUnchecked(f)\n\n// Where the last portion of a row matches in a path: the start of the\n// last portion of the path, or of the one before a trailing `/`. -1 if\n// it matches neither.\nconst endIndex = (\n  p: string | Matcher,\n  last: string,\n  lastStart: number,\n  prev: string | undefined,\n  prevStart: number,\n) =>\n  portionMatch(p, last) ? lastStart\n  : prev !== undefined && portionMatch(p, prev) ? prevStart\n  : -1\n\nconst isDots = (p: string) => p === '.' || p === '..'\n\n// a Windows drive letter portion, like `c:`\nconst isDrive = (p: ParseReturn | undefined) =>\n  typeof p === 'string' && /^[a-z]:$/i.test(p)\n\n// true for the `UNC` portion of a long UNC root, //?/UNC/host/share\nconst isLongUNC = (p: ParseReturn | undefined) =>\n  typeof p === 'string' && /^unc$/i.test(p)\n\n// The index of the host in a row or split path that starts with a\n// Windows UNC root: 2 for `//host/share`, and 4 for\n// `//?/UNC/host/share`. Otherwise -1. `//?/c:` is not one.\nconst uncHost = (p: ParseReturn[]) => {\n  if (p[0] !== '' || p[1] !== '') return -1\n  const h =\n    p[2] !== '?' ? 2\n    : isLongUNC(p[3]) ? 4\n    : -1\n  const host = p[h]\n  const share = p[h + 1]\n  return (\n      h !== -1 &&\n        host !== undefined &&\n        host !== '' &&\n        host !== GLOBSTAR &&\n        share !== undefined &&\n        share !== '' &&\n        share !== GLOBSTAR\n    ) ?\n      h\n    : -1\n}\n\n// true if ** can walk the path portion: not `.` or `..`, and not a\n// dotfile unless `dot` is set\nconst walkable = (p: string, dot: boolean) =>\n  !isDots(p) && (dot || !p.startsWith('.'))\n\n// True if a portion of the path from `start` to `end` can not be\n// walked by **: one that starts with `.`, or with `dot`, one that is\n// `.` or `..`. `start` is the start of a portion, and `end` is the end\n// of the path, or just after a separator.\nconst dotPortion = (\n  f: string,\n  start: number,\n  end: number,\n  dot: boolean,\n  sep: PathSeps,\n) => {\n  for (let k = start; k < end;) {\n    if (f.charCodeAt(k) === 46) {\n      if (!dot) return true\n      const n = f.charCodeAt(k + 1) === 46 ? k + 2 : k + 1\n      if (n >= end || isSep(f.charCodeAt(n), sep)) return true\n    }\n    // the start of the next portion, after any run of separators\n    const s = nextSep(f, k, sep)\n    if (s === -1) return false\n    k = s + 1\n    while (k < end && isSep(f.charCodeAt(k), sep)) k++\n  }\n  return false\n}\n\n/**\n * The separators that a path has: only `/`, only `\\` (a Windows path\n * with no `/`), or both. Scanning for the ones it has is faster.\n */\nexport type PathSeps = '/' | '\\\\' | 'both'\n\nconst isSep = (c: number, sep: PathSeps) =>\n  sep === '/' ? c === 47\n  : sep === '\\\\' ? c === 92\n  : c === 47 || c === 92\n\n// the index of the first separator at or after `from`, or -1\nconst nextSep = (f: string, from: number, sep: PathSeps) => {\n  if (sep !== 'both') return f.indexOf(sep, from)\n  const s = f.indexOf('/', from)\n  const b = f.indexOf('\\\\', from)\n  return (\n    s === -1 ? b\n    : b === -1 ? s\n    : Math.min(s, b)\n  )\n}\n\n// the index of the last separator at or before `from`, or -1\nconst lastSep = (f: string, from: number, sep: PathSeps) =>\n  sep !== 'both' ?\n    f.lastIndexOf(sep, from)\n  : Math.max(f.lastIndexOf('/', from), f.lastIndexOf('\\\\', from))\n\n/**\n * A pattern row split on its first and last `**`, from a start\n * index. Each body segment has the number of path portions that it\n * and the ones after it need, to find the last index where it can\n * start in a path.\n */\nexport type GlobstarParts = {\n  head: ParseReturn[]\n  body: ParseReturn[]\n  tail: ParseReturn[]\n  segments: [segment: ParseReturn[], need: number][]\n}\nexport type ParseReturn = ParseReturnFiltered | false\n\n// What parse() returns in place of a Matcher while make() builds and\n// merges the rows. Most of the Matchers in rows that are merged would\n// never be used, so they are only made for the rows that are left.\nconst PENDING = {} as Matcher\n\nexport class Minimatch {\n  options: MinimatchOptions\n  set: ParseReturnFiltered[][]\n  pattern: string\n\n  windowsPathsNoEscape: boolean\n  nonegate: boolean\n  negate: boolean\n  comment: boolean\n  empty: boolean\n  preserveMultipleSlashes: boolean\n  partial: boolean\n  globSet: string[]\n  globParts: string[][]\n  nocase: boolean\n\n  isWindows: boolean\n  platform: Platform\n  windowsNoMagicRoot: boolean\n  maxGlobstarRecursion: number\n  // the path can be checked against the last portion, and the string\n  // portions, of each row before it is split. See #canMatch.\n  #endCheck: boolean\n  #literalCheck: boolean\n  // level 2 resolves `.` and `..` portions in the path\n  #level2: boolean\n  // the unicode normalization form, if any\n  #form: Form | undefined\n  // the string portions of each row in the set\n  #literals: string[][] = []\n  // the rows that #canMatch can match without splitting the path\n  #shapes: (RowShape | undefined)[] = []\n  // the rows whose last portion can be checked against the path's\n  #endRows: boolean[] = []\n  // brace expansion can make the same portion in many rows, so they\n  // share one Matcher, and the states that it caches\n  #matchers = new Map()\n  // parse() returns PENDING in place of a Matcher\n  #pending = false\n  // the char that marks numeric ranges in globSet, if any\n  #rangeMark?: string\n  // the GlobstarParts of each pattern row, by start index and partial\n  #globstarParts = new WeakMap()\n\n  constructor(pattern: string, options: MinimatchOptions = {}) {\n    assertValidPattern(pattern)\n\n    options = options || {}\n    this.options = options\n    this.maxGlobstarRecursion =\n      options.maxGlobstarRecursion ?? DEFAULT_GLOB_STAR_RECURSION_MAX\n    this.pattern = pattern\n    this.platform = options.platform || defaultPlatform\n    this.isWindows = this.platform === 'win32'\n    this.windowsPathsNoEscape =\n      !!options.windowsPathsNoEscape || options[AWE_KEY] === false\n    if (this.windowsPathsNoEscape) {\n      this.pattern = this.pattern.replace(/\\\\/g, '/')\n    }\n    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n    this.negate = false\n    this.nonegate = !!options.nonegate\n    this.comment = false\n    this.empty = false\n    this.partial = !!options.partial\n    this.nocase = !!this.options.nocase\n    this.windowsNoMagicRoot =\n      options.windowsNoMagicRoot !== undefined ?\n        options.windowsNoMagicRoot\n      : !!(this.isWindows && this.nocase)\n\n    this.globSet = []\n    this.globParts = []\n    this.set = []\n    this.#endCheck = !this.preserveMultipleSlashes\n    this.#level2 = (options.optimizationLevel ?? 1) >= 2\n    const n = options.normalize\n    this.#form = n === true ? 'NFC' : n || undefined\n\n    // make the set of Matchers etc.\n    this.make()\n\n    // On Windows, the portions of a row up to its drive letter or UNC\n    // share are skipped or compared without case, if the path has one\n    // too. So the checks only use the portions after it.\n    const drives = this.set.map(row => this.#rootIndex(row))\n    this.#endRows = this.set.map(\n      (row, r) => this.#endCheck && row.length - 1 > drives[r]!,\n    )\n    // with the end check, the last portion is already checked\n    this.#literals = this.set.map((row, r) => {\n      const end = this.#endRows[r] ? row.length - 1 : row.length\n      const lits = row\n        .slice(drives[r]! + 1, end)\n        .filter((p): p is string => typeof p === 'string' && !!p)\n      return [...new Set(lits)]\n    })\n    this.#literalCheck = this.#literals.some(l => l.length)\n    this.#shapes = this.set.map((row, r) => {\n      const [p0, p1, p2] = row\n      if (this.#endRows[r] && row.length === 2) {\n        if (p0 === GLOBSTAR && p1 !== GLOBSTAR) return 'tail'\n      }\n      // the basename of a path that is split on / is its last portion,\n      // or the one before a trailing /, the same as the end check\n      if (\n        this.#endRows[r] &&\n        options.matchBase &&\n        row.length === 1 &&\n        p0 !== GLOBSTAR &&\n        p0 !== ''\n      ) {\n        return 'base'\n      }\n      // the portion must not be a root, or '', which can be a\n      // different portion on Windows (where //x paths get an extra '')\n      if (!this.#endCheck || drives[r] !== -1) return undefined\n      if (\n        row.length === 3 &&\n        p0 === GLOBSTAR &&\n        p2 === GLOBSTAR &&\n        p1 !== GLOBSTAR &&\n        p1 !== '' &&\n        // the portion between is only matched below this limit\n        this.maxGlobstarRecursion > 0\n      ) {\n        return 'mid'\n      }\n      if (\n        row.length === 2 &&\n        p1 === GLOBSTAR &&\n        p0 !== GLOBSTAR &&\n        p0 !== ''\n      ) {\n        return 'head'\n      }\n      return undefined\n    })\n  }\n\n  // a string portion of a pattern, normalized if the option is set\n  #norm(p: string) {\n    return this.#form ? p.normalize(this.#form) : p\n  }\n\n  // On Windows, the index of the last root portion of a row, as\n  // #matchRow finds it: 0 for `c:/...`, 3 for `//?/c:/...` and\n  // `//host/share/...`, and 5 for `//?/UNC/host/share/...`. Otherwise\n  // -1.\n  #rootIndex(row: ParseReturn[]) {\n    if (!this.isWindows) return -1\n    if (isDrive(row[0])) return 0\n    const uncDrive =\n      row[0] === '' && row[1] === '' && row[2] === '?' && isDrive(row[3])\n    if (uncDrive) return 3\n    const h = uncHost(row)\n    return h === -1 ? -1 : h + 1\n  }\n\n  hasMagic(): boolean {\n    if (this.options.magicalBraces && this.set.length > 1) {\n      return true\n    }\n    for (const pattern of this.set) {\n      for (const part of pattern) {\n        if (typeof part !== 'string') return true\n      }\n    }\n    return false\n  }\n\n  make() {\n    const pattern = this.pattern\n    const options = this.options\n\n    // empty patterns and comments match nothing.\n    if (!options.nocomment && pattern.charAt(0) === '#') {\n      this.comment = true\n      return\n    }\n\n    if (!pattern) {\n      this.empty = true\n      return\n    }\n\n    // step 1: figure out negation, etc.\n    this.parseNegate()\n\n    // step 2: expand braces\n    this.globSet = [...new Set(this.#expandBraces())]\n\n    // step 3: now we have a set, so turn each one into a series of\n    // path-portion matching patterns.\n    // These will be Matchers, except in the case of \"**\", which is\n    // set to the GLOBSTAR object for globstar behavior,\n    // and will not contain any / characters\n    //\n    // First, we preprocess to make the glob pattern sets a bit simpler\n    // and deduped.  There are some perf-killing patterns that can cause\n    // problems with a glob walk, but we can simplify them down a bit.\n    const rawGlobParts = this.globSet.map(s => this.#slashSplit(s))\n    this.globParts = this.preprocess(rawGlobParts)\n\n    // glob --> Matchers\n    this.#pending = true\n    let set = this.globParts.map((s, _, __) => {\n      if (this.isWindows && this.windowsNoMagicRoot) {\n        // check if it's a drive or unc path. The root of a long UNC\n        // path, //?/UNC/host/share, is 6 portions.\n        const n = s[2] === '?' && isLongUNC(s[3]) ? 6 : 4\n        const isUNC =\n          s[0] === '' &&\n          s[1] === '' &&\n          (s[2] === '?' || !globMagic.test(s[2])) &&\n          s.slice(3, n).every(p => !globMagic.test(p))\n        const isDrive = /^[a-z]:/i.test(s[0])\n        if (isUNC) {\n          return [\n            ...s.slice(0, n).map(p => this.#norm(p)),\n            ...s.slice(n).map(ss => this.parse(ss)),\n          ]\n        } else if (isDrive) {\n          return [\n            this.#norm(s[0]!),\n            ...s.slice(1).map(ss => this.parse(ss)),\n          ]\n        }\n      }\n      return s.map(ss => this.parse(ss))\n    })\n\n    // filter out everything that didn't compile properly.\n    this.set = set.filter(\n      s => s.indexOf(false) === -1,\n    ) as ParseReturnFiltered[][]\n\n    // do not treat the ? in UNC paths as magic\n    if (this.isWindows) {\n      for (let i = 0; i < this.set.length; i++) {\n        const p = this.set[i]\n        if (\n          p[0] === '' &&\n          p[1] === '' &&\n          this.globParts[i][2] === '?' &&\n          (isDrive(p[3]) || isLongUNC(this.globParts[i][3]))\n        ) {\n          if (isLongUNC(this.globParts[i][3])) p[3] = 'UNC'\n          p[2] = '?'\n        }\n      }\n    }\n\n    // with noext, `@(...)` would be literal\n    if (!options.noext) this.mergeRows()\n\n    this.#pending = false\n    this.set.forEach((row, i) => {\n      for (let k = 0; k < row.length; k++) {\n        if (row[k] === PENDING) {\n          row[k] = this.parse(this.globParts[i]![k]!) as Matcher\n        }\n      }\n    })\n  }\n\n  // Merge rows that only differ in one portion, where each of them\n  // is a Matcher, into one row that matches any of them with\n  // `@(a|b|...)`. Then a path is only walked once for all of them,\n  // for example with `**/*.{js,ts}`.\n  mergeRows() {\n    let merged = true\n    while (merged) {\n      merged = false\n      // a single row cannot be merged with anything\n      if (this.set.length < 2) return\n      let keys = this.#mergeKeys()\n      const len = Math.max(0, ...this.set.map(r => r.length))\n      for (let k = 0; k < len; k++) {\n        // the rows that are the same other than at portion k, keyed\n        // by the ids of the parts before k and the parts after k,\n        // which are at most the number of rows\n        const groups = new Map()\n        const R = this.set.length + 1\n        this.set.forEach((row, i) => {\n          if (\n            !(row[k] instanceof Matcher || row[k] === PENDING) ||\n            !extSafe(this.globParts[i]![k]!)\n          ) {\n            return\n          }\n          const { pre, suf } = keys[i]!\n          const key = pre[k]! * R + suf[k + 1]!\n          const g = groups.get(key)\n          if (g) g.push(i)\n          else groups.set(key, [i])\n        })\n        const drop = new Set()\n        for (const g of groups.values()) {\n          if (g.length < 2) continue\n          const [first, ...rest] = g as [number, ...number[]]\n          const alts = g.map(i => this.globParts[i]![k]!)\n          const glob = `@(${alts.join('|')})`\n          // merging is only an optimization, so leave the rows as they\n          // are if the merged portion would have too many extglobs\n          if (extglobCount(glob) > MAX_EXTGLOBS) continue\n          this.globParts[first]![k] = glob\n          this.set[first]![k] = this.parse(glob) as Matcher\n          for (const i of rest) drop.add(i)\n        }\n        if (drop.size) {\n          merged = true\n          this.set = this.set.filter((_, i) => !drop.has(i))\n          this.globParts = this.globParts.filter((_, i) => !drop.has(i))\n          // every merge drops a row, so this happens at most once per row\n          if (this.set.length < 2) return\n          keys = this.#mergeKeys()\n        }\n      }\n    }\n  }\n\n  // For each row, number ids for its prefixes and suffixes, such that\n  // pre[k] identifies parts[0..k) and suf[k] identifies parts[k..n).\n  // Two rows are the same other than at portion k exactly when they\n  // have the same pre[k] and suf[k + 1]. This is linear in the size of\n  // the rows, where joining the whole row for every k was quadratic.\n  #mergeKeys(): { pre: number[]; suf: number[] }[] {\n    const partIds = new Map()\n    const ids = this.globParts.map(parts =>\n      parts.map(s => {\n        let id = partIds.get(s)\n        if (id === undefined) partIds.set(s, (id = partIds.size))\n        return id\n      }),\n    )\n    // ids are only compared at the same k, so they are numbered per\n    // portion, with 0 for the empty prefix or suffix. Then they are\n    // at most the number of rows, and id * P + part id is a safe\n    // integer key for any set that fits in memory.\n    const P = partIds.size\n    const len = Math.max(0, ...ids.map(r => r.length))\n    const keys = ids.map(r => ({\n      pre: [0] as number[],\n      suf: new Array(r.length + 1).fill(0),\n    }))\n    for (let k = 0; k < len; k++) {\n      const m = new Map()\n      ids.forEach((r, i) => {\n        if (k >= r.length) return\n        const { pre } = keys[i]!\n        const key = pre[k]! * P + r[k]!\n        let id = m.get(key)\n        if (id === undefined) m.set(key, (id = m.size + 1))\n        pre.push(id)\n      })\n    }\n    for (let k = len - 1; k >= 0; k--) {\n      const m = new Map()\n      ids.forEach((r, i) => {\n        if (k >= r.length) return\n        const { suf } = keys[i]!\n        const key = suf[k + 1]! * P + r[k]!\n        let id = m.get(key)\n        if (id === undefined) m.set(key, (id = m.size + 1))\n        suf[k] = id\n      })\n    }\n    return keys\n  }\n\n  // various transforms to equivalent pattern sets that are\n  // faster to process in a filesystem walk.  The goal is to\n  // eliminate what we can, and push all ** patterns as far\n  // to the right as possible, even if it increases the number\n  // of patterns that we have to process.\n  preprocess(globParts: string[][]) {\n    // if we're not in globstar mode, then turn ** into *\n    if (this.options.noglobstar) {\n      for (const partset of globParts) {\n        for (let j = 0; j < partset.length; j++) {\n          if (partset[j] === '**') {\n            partset[j] = '*'\n          }\n        }\n      }\n    }\n\n    const { optimizationLevel = 1 } = this.options\n\n    if (optimizationLevel >= 2) {\n      // aggressive optimization for the purpose of fs walking\n      globParts = this.firstPhasePreProcess(globParts)\n      globParts = this.secondPhasePreProcess(globParts)\n    } else if (optimizationLevel >= 1) {\n      // just basic optimizations to remove some .. parts\n      globParts = this.levelOneOptimize(globParts)\n    } else {\n      // just collapse multiple ** portions into one\n      globParts = this.adjascentGlobstarOptimize(globParts)\n    }\n\n    return globParts\n  }\n\n  // just get rid of adjascent ** portions\n  adjascentGlobstarOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      let gs: number = -1\n      while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n        let i = gs\n        while (parts[i + 1] === '**') {\n          i++\n        }\n        if (i !== gs) {\n          parts.splice(gs, i - gs)\n        }\n      }\n      return parts\n    })\n  }\n\n  // get rid of adjascent ** and resolve .. portions\n  levelOneOptimize(globParts: string[][]) {\n    return globParts.map(parts => {\n      // .. can not remove the root of a Windows path\n      const root = this.#rootIndex(parts) + 1\n      parts = parts.reduce((set: string[], part) => {\n        const prev = set[set.length - 1]\n        if (part === '**' && prev === '**') {\n          return set\n        }\n        if (part === '..') {\n          if (\n            set.length > root &&\n            prev &&\n            prev !== '..' &&\n            prev !== '.' &&\n            prev !== '**'\n          ) {\n            set.pop()\n            return set\n          }\n        }\n        set.push(part)\n        return set\n      }, [])\n      return parts.length === 0 ? [''] : parts\n    })\n  }\n\n  // Check the path against each row before it is split. 'no' if no\n  // row can match, so it does not need to be split. 'yes' if a row of\n  // `**` and one more portion matches. 'maybe' if it must be split to\n  // know. None of this applies with partial, where the path can end\n  // before the row does.\n  //\n  // On Windows, `\\` is a separator in the path too, and the portions of\n  // a row up to its drive letter or UNC share are not checked (see\n  // #rootIndex).\n  //\n  // Each string portion of a row must be a portion of the path, so the\n  // path must contain it. Level 2 can only take portions out of the\n  // path, so this is still true then.\n  //\n  // The last portion of a row must match the last portion of the path,\n  // or the one before a trailing `/` (as a/* and a/**/* match a/b/).\n  // This does not apply to rows that end in **, rows that end in a\n  // root, or preserveMultipleSlashes (which can leave more\n  // than one '' at the end). At level 2, it does not apply if that\n  // portion is `.` or `..`, which can be\n  // resolved away. Level 2 only takes other portions out of the\n  // middle of the path.\n  //\n  // A row of `**/x` then matches if the ** can walk the portions\n  // before the one that x matches, the same as #matchGlobstar. At\n  // level 2, this is only known if none of them are `.` or `..`, so\n  // that the path does not change when it is resolved.\n  #canMatch(f: string): 'no' | 'yes' | 'maybe' {\n    const sep: PathSeps =\n      !this.isWindows || !f.includes('\\\\') ? '/'\n      : f.includes('/') ? 'both'\n      : '\\\\'\n    // the portions that f.split(/\\/+/) would end with, and where they\n    // start in f, found when a row needs them. `ends` is 0 until they\n    // are found, then 1, or -1 if they can not be used.\n    let ends = this.#endCheck ? 0 : -1\n    let last = ''\n    let lastStart = 0\n    let prev: string | undefined\n    let prevStart = 0\n    const dot = !!this.options.dot\n    // A string compare is cheaper than includes(), and a Matcher test\n    // costs more, so the cheaper check goes first.\n    ROWS: for (let r = 0; r < this.set.length; r++) {\n      const row = this.set[r]!\n      const p = row[row.length - 1]\n      let end = ends !== -1 && this.#endRows[r]! && p !== GLOBSTAR\n      if (end && ends === 0) {\n        const i = lastSep(f, f.length, sep)\n        lastStart = i + 1\n        last = f.slice(lastStart)\n        if (last === '' && i >= 0) {\n          let j = i\n          while (j > 0 && isSep(f.charCodeAt(j - 1), sep)) j--\n          prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep) + 1\n          prev = f.slice(prevStart, j)\n        }\n        const resolves =\n          this.#level2 &&\n          (isDots(last) ||\n            (last === '' && prev !== undefined && isDots(prev)))\n        ends = resolves ? -1 : 1\n        end = !resolves\n      }\n      let tailStart = -1\n      if (end && typeof p === 'string') {\n        tailStart = endIndex(p, last, lastStart, prev, prevStart)\n        if (tailStart === -1) continue\n      }\n      if (this.#literalCheck) {\n        for (const l of this.#literals[r]!) {\n          if (!f.includes(l)) continue ROWS\n        }\n      }\n      if (end && typeof p === 'object') {\n        tailStart = endIndex(p, last, lastStart, prev, prevStart)\n        if (tailStart === -1) continue\n      }\n      const shape = this.#shapes[r]\n      if (shape === 'base' && end) return 'yes'\n      if (shape === 'tail' && end) {\n        if (this.#level2 && dotPortion(f, 0, tailStart, true, sep)) {\n          return 'maybe'\n        }\n        if (!dotPortion(f, 0, tailStart, dot, sep)) return 'yes'\n        continue\n      }\n      if (shape === 'mid' || shape === 'head') {\n        const m = this.#walk(f, row, shape === 'head', dot, sep)\n        if (m !== 'no') return m\n        continue\n      }\n      return 'maybe'\n    }\n    return 'no'\n  }\n\n  // Match a row of a known shape against the split path, the same as\n  // #matchGlobstar and #matchGlobStarBodySections do. None of these\n  // rows have a drive letter, so they start at the first portion.\n  #matchShape(\n    file: string[],\n    row: ParseReturnFiltered[],\n    shape: 'tail' | 'mid' | 'head',\n  ): boolean {\n    const dot = !!this.options.dot\n    const n = file.length\n    if (shape === 'head') {\n      // x, then at least one portion that ** can walk\n      if (n < 2 || !portionMatch(row[0] as string | Matcher, file[0]!)) {\n        return false\n      }\n      for (let i = 1; i < n; i++)\n        if (!walkable(file[i]!, dot)) return false\n      return true\n    }\n    const x = row[1] as string | Matcher\n    if (shape === 'tail') {\n      // x is the last portion, or the one before a trailing ''\n      let t = n - 1\n      if (!portionMatch(x, file[t]!)) {\n        if (file[t] !== '' || n === 1 || !portionMatch(x, file[--t]!)) {\n          return false\n        }\n      }\n      for (let i = 0; i < t; i++)\n        if (!walkable(file[i]!, dot)) return false\n      return true\n    }\n    // mid: the first x that ** can walk to, with a portion after it,\n    // and ** can walk all of those\n    for (let k = 0; k < n; k++) {\n      if (portionMatch(x, file[k]!) && k + 1 < n) {\n        let i = k + 1\n        while (i < n && walkable(file[i]!, dot)) i++\n        if (i === n) return true\n      }\n      if (!walkable(file[k]!, dot)) return false\n    }\n    return false\n  }\n\n  // Match a row of `**/x/**` or `x/**` against the path, the same as\n  // #matchGlobstar and #matchGlobStarBodySections do once it is split.\n  // x must match a portion (the first one, for `x/**`), the ** before\n  // it must be able to walk the portions before that one, and there\n  // must be a portion after it, which the ** after it can walk. At\n  // level 2, this is only known if no portion is `.` or `..`.\n  #walk(\n    f: string,\n    row: ParseReturnFiltered[],\n    head: boolean,\n    dot: boolean,\n    sep: PathSeps,\n  ): 'yes' | 'no' | 'maybe' {\n    if (this.#level2 && dotPortion(f, 0, f.length, true, sep))\n      return 'maybe'\n    const x = row[head ? 0 : 1] as string | Matcher\n    // the last portion has none after it, so it can not be x\n    let s = 0\n    for (let e = nextSep(f, s, sep); e !== -1; e = nextSep(f, s, sep)) {\n      // the start of the next portion\n      let next = e + 1\n      while (next < f.length && isSep(f.charCodeAt(next), sep)) next++\n      const hit =\n        typeof x === 'string' ?\n          e - s === x.length && f.startsWith(x, s)\n        : e > s && x.testUnchecked(f.slice(s, e))\n      if (hit && !dotPortion(f, next, f.length, dot, sep)) return 'yes'\n      if (head || dotPortion(f, s, next, dot, sep)) return 'no'\n      s = next\n    }\n    return 'no'\n  }\n\n  // the last split, if it was the same path with the same split\n  // settings\n  #cachedSplit(f: string) {\n    const last = lastSplit\n    return (\n        last?.f === f &&\n          last.isWindows === this.isWindows &&\n          last.preserveMultipleSlashes === this.preserveMultipleSlashes &&\n          last.normalize === this.#form\n      ) ?\n        last\n      : undefined\n  }\n\n  // split a path for match(), and keep the parts for the next call\n  #split(f: string) {\n    const { isWindows, preserveMultipleSlashes } = this\n    // windows: need to use /, not \\\n    let parts = this.#slashSplit(isWindows ? f.split('\\\\').join('/') : f)\n    // normalize each portion, so that a char that normalizes to `/`\n    // does not make a new portion\n    const normalize = this.#form\n    if (normalize) parts = parts.map(p => p.normalize(normalize))\n    lastSplit = {\n      f,\n      isWindows,\n      preserveMultipleSlashes,\n      normalize,\n      parts,\n    }\n    return lastSplit\n  }\n\n  // resolve `.` and `..` portions of a path, for level 2\n  #levelTwoFileOptimize(file: string[]) {\n    // work on a copy, so that the cached parts do not change\n    const parts = [...file]\n    let didSomething: boolean = false\n\n    do {\n      didSomething = false\n      // 
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      // .. can not remove the root of a Windows path\n      const root = this.#rootIndex(parts) + 1\n      let dd: number = root\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd = Math.max(dd - 2, root)\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    // each **/.. split doubles the patterns, and adds a copy of the\n    // whole pattern. Throw if either gets too large. A partial split\n    // would match some paths and not others, depending on which rows\n    // the pass reached first.\n    const { braceExpandMax = DEFAULT_BRACE_EXPAND_MAX } = this.options\n    let splitCells = 0\n    const maxSplitCells = 1_000_000\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          // Check before changing parts or allocating the new row.\n          const addedCells = parts.length - 1\n          if (\n            globParts.length >= braceExpandMax ||\n            splitCells + addedCells > maxSplitCells\n          ) {\n            throw new RangeError(\n              `optimizationLevel 2: too many patterns from '**/..'`,\n            )\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          splitCells += addedCells\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        // .. can not remove the root of a Windows path\n        const root = this.#rootIndex(parts) + 1\n        let dd: number = root\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd = Math.max(dd - 2, root)\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/,
/} -> 
/\n  // {
/*/,
/

/} ->

/*/\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    const keys = new Set()\n    const rows = globParts.filter(parts => {\n      const key = parts.join('/')\n      if (keys.has(key)) return false\n      keys.add(key)\n      return true\n    })\n\n    // A row is covered by another row that has `*` at some positions,\n    // and is the same at all others. Collect each distinct set of `*`\n    // positions, then look up each row with `*` put at those positions.\n    const stars = new Map()\n    for (const parts of rows) {\n      const s: number[] = []\n      for (let i = 0; i < parts.length; i++) {\n        if (parts[i] === '*') s.push(i)\n      }\n      if (s.length) stars.set(s.join(','), s)\n    }\n    // Each row is checked against each set of `*` positions, so skip\n    // this if there are too many. The patterns match the same paths\n    // either way.\n    if (!stars.size || rows.length * stars.size > 100_000) return rows\n\n    const { dot } = this.options\n    return rows.filter(parts => {\n      for (const s of stars.values()) {\n        if (s[s.length - 1]! >= parts.length) continue\n        const c = [...parts]\n        let ok = true\n        let changed = false\n        for (const i of s) {\n          const p = parts[i]!\n          if (p === '*') continue\n          if (!p || p === '**' || (!dot && p.startsWith('.'))) {\n            ok = false\n            break\n          }\n          c[i] = '*'\n          changed = true\n        }\n        if (ok && changed && keys.has(c.join('/'))) return false\n      }\n      return true\n    })\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // Match the parts of a path against one row of the set. `resolved`\n  // is the parts after level 2 resolves `.` and `..` in them, or the\n  // same parts below level 2. Set partial to true to test if, for\n  // example, \"/a/b\" matches the start of \"/*/b/*/d\". Partial means, if\n  // you run out of file before you run out of pattern, then that's\n  // fine, as long as all the parts match.\n  #matchRow(\n    file: string[],\n    resolved: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n  ) {\n    let fileStartIndex = 0\n    let patternStartIndex = 0\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa, and\n    // //?/UNC/host/share/... can match //host/share/... and vice versa.\n    // Drive letters in absolute drive or unc paths, and the host and\n    // share of UNC paths, are always compared case-insensitively.\n    const fh = this.isWindows ? uncHost(resolved) : -1\n    const ph = fh === -1 ? -1 : uncHost(pattern)\n    if (ph !== -1) {\n      const host = pattern[ph]\n      const share = pattern[ph + 1]\n      if (typeof host !== 'string' || typeof share !== 'string') {\n        // a host or share with magic is matched as usual\n        fileStartIndex = fh\n        patternStartIndex = ph\n      } else if (\n        resolved[fh]!.toLowerCase() === host.toLowerCase() &&\n        resolved[fh + 1]!.toLowerCase() === share.toLowerCase()\n      ) {\n        fileStartIndex = fh + 2\n        patternStartIndex = ph + 2\n      }\n    } else if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi =\n        fileUNC ? 3\n        : fileDrive ? 0\n        : undefined\n      const pdi =\n        patternUNC ? 3\n        : patternDrive ? 0\n        : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        // the drives match, so start matching after them\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          patternStartIndex = pdi + 1\n          fileStartIndex = fdi + 1\n        }\n      }\n    }\n\n    // the drive letters are found in the parts before level 2 resolves\n    // them, and the match uses the resolved parts\n    file = resolved\n\n    if (pattern.includes(GLOBSTAR)) {\n      return this.#matchGlobstar(\n        file,\n        pattern,\n        partial,\n        fileStartIndex,\n        patternStartIndex,\n      )\n    }\n\n    return this.#matchOne(\n      file,\n      pattern,\n      partial,\n      fileStartIndex,\n      patternStartIndex,\n    )\n  }\n\n  #matchGlobstar(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n  ) {\n    const { head, body, tail, segments } = this.#getGlobstarParts(\n      pattern,\n      partial,\n      patternIndex,\n    )\n\n    // check the head, from the current file/pattern index.\n    if (head.length) {\n      const headEnd = fileIndex + head.length\n      if (!this.#matchOne(file, head, partial, fileIndex, 0, headEnd)) {\n        return false\n      }\n      fileIndex += head.length\n      patternIndex += head.length\n    }\n    // now we know the head matches!\n\n    // if the last portion is not empty, it MUST match the end\n    // check the tail\n    let fileTailMatch: number = 0\n    if (tail.length) {\n      // if head + tail > file, then we cannot possibly match\n      if (tail.length + fileIndex > file.length) return false\n\n      // try to match the tail\n      let tailStart = file.length - tail.length\n      if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n        fileTailMatch = tail.length\n      } else {\n        // affordance for stuff like a/**/* matching a/b/\n        // if the last file portion is '', and there's more to the pattern\n        // then try without the '' bit.\n        if (\n          file[file.length - 1] !== '' ||\n          fileIndex + tail.length === file.length\n        ) {\n          return false\n        }\n        tailStart--\n        if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n          return false\n        }\n        fileTailMatch = tail.length + 1\n      }\n    }\n\n    // now we know the tail matches!\n\n    // the middle is zero or more portions wrapped in **, possibly\n    // containing more ** sections.\n    // so a/**/b/**/c/**/d has become **/b/**/c/**\n    // if it's empty, it means a/**/b, just verify we have no bad dots\n    // if there's no tail, so it ends on /**, then we must have *something*\n    // after the head, or it's not a matc\n    if (!body.length) {\n      let sawSome = !!fileTailMatch\n      for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n        const f = String(file[i])\n        sawSome = true\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      // in partial mode, we just need to get past all file parts\n      return partial || sawSome\n    }\n\n    // now we know that there's one or more body sections, which can\n    // be matched anywhere from the 0 index (because the head was pruned)\n    // through to the length-fileTailMatch index.\n    return !!this.#matchGlobStarBodySections(\n      file,\n      segments,\n      file.length - fileTailMatch,\n      fileIndex,\n      0,\n      partial,\n      0,\n      !!fileTailMatch,\n      new Set(),\n    )\n  }\n\n  // Split the pattern into head, tail, and middle of ** delimited\n  // parts. The tail has to be at the end, and the others just have to\n  // be found in order from the head. These only depend on the pattern\n  // row, so they are kept for the next path.\n  #getGlobstarParts(\n    pattern: ParseReturn[],\n    partial: boolean,\n    patternIndex: number,\n  ): GlobstarParts {\n    let byStart = this.#globstarParts.get(pattern)\n    if (!byStart) {\n      byStart = []\n      this.#globstarParts.set(pattern, byStart)\n    }\n    const key = patternIndex * 2 + (partial ? 1 : 0)\n    const found = byStart[key]\n    if (found) return found\n\n    const firstgs = pattern.indexOf(GLOBSTAR, patternIndex)\n    const lastgs = pattern.lastIndexOf(GLOBSTAR)\n    const head = pattern.slice(patternIndex, firstgs)\n    const body = pattern.slice(firstgs + 1, partial ? undefined : lastgs)\n    const tail = partial ? [] : pattern.slice(lastgs + 1)\n\n    // split the body up into sections, and note the number of\n    // portions that must come after the start of each one\n    const segments: [ParseReturn[], number][] = [[[], 0]]\n    let current = segments[0]!\n    let nonGsParts = 0\n    const nonGsPartsSums: number[] = [0]\n    for (const b of body) {\n      if (b === GLOBSTAR) {\n        nonGsPartsSums.push(nonGsParts)\n        current = [[], 0]\n        segments.push(current)\n      } else {\n        current[0].push(b)\n        nonGsParts++\n      }\n    }\n    // the portions in this section and the ones after it\n    segments.forEach((b, i) => {\n      b[1] = nonGsParts - (nonGsPartsSums[i] as number)\n    })\n\n    const parts = { head, body, tail, segments }\n    byStart[key] = parts\n    return parts\n  }\n\n  // return false for \"nope, not matching\"\n  // return null for \"not matching, cannot keep trying\"\n  #matchGlobStarBodySections(\n    file: string[],\n    // pattern section, and the portions that it and the rest need\n    bodySegments: [ParseReturn[], number][],\n    // the end of the file portions that the body can match\n    fileLength: number,\n    fileIndex: number,\n    bodyIndex: number,\n    partial: boolean,\n    globStarDepth: number,\n    sawTail: boolean,\n    // the places that a walk has already tried, as\n    // bodyIndex * (file.length + 1) + fileIndex. A walk from a place\n    // does the same no matter how it got there, and it only comes back\n    // if it found no match, so a walk that gets to one stops.\n    tried: Set,\n  ): boolean | null {\n    // take the first body segment, and walk from fileIndex to its \"after\"\n    // value at the end\n    // If it doesn't match at that position, we increment, until we hit\n    // that final possible position, and give up.\n    // If it does match, then advance and try to rest.\n    // If any of them fail we keep walking forward.\n    // this is still a bit recursively painful, but it's more constrained\n    // than previous implementations, because we never test something that\n    // can't possibly be a valid matching condition.\n    const bs = bodySegments[bodyIndex]\n    if (!bs) {\n      // with partial, the body is the rest of the pattern, so it\n      // matches if no portions are left, or only the '' of a trailing\n      // / (as a/* matches a/b/). A ** at the end walks them as its own\n      // empty section.\n      if (partial) {\n        return (\n          fileIndex >= fileLength ||\n          (fileIndex === fileLength - 1 && file[fileIndex] === '')\n        )\n      }\n      // just make sure that there's no bad dots before the tail\n      for (let i = fileIndex; i < fileLength; i++) {\n        sawTail = true\n        const f = file[i]\n        if (\n          f === '.' ||\n          f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      return sawTail\n    }\n\n    // have a non-globstar body section to test, up to the last index\n    // where it can start\n    const [body, need] = bs\n    // with partial, the path can end before the body does\n    const after = partial ? fileLength : fileLength - need\n    while (fileIndex <= after) {\n      const key = bodyIndex * (file.length + 1) + fileIndex\n      if (tried.has(key)) return false\n      tried.add(key)\n      const m = this.#matchOne(\n        file,\n        body,\n        partial,\n        fileIndex,\n        0,\n        fileIndex + body.length,\n      )\n      // if limit exceeded, no match. intentional false negative,\n      // acceptable break in correctness for security.\n      if (m && globStarDepth < this.maxGlobstarRecursion) {\n        // match! see if the rest match. if so, we're done!\n        const sub = this.#matchGlobStarBodySections(\n          file,\n          bodySegments,\n          fileLength,\n          fileIndex + body.length,\n          bodyIndex + 1,\n          partial,\n          globStarDepth + 1,\n          sawTail,\n          tried,\n        )\n        if (sub !== false) {\n          return sub\n        }\n      }\n      // the ** does not walk past the last place the body can start\n      if (fileIndex === after) break\n      const f = file[fileIndex]!\n      if (\n        f === '.' ||\n        f === '..' ||\n        (!this.options.dot && f.startsWith('.'))\n      ) {\n        return false\n      }\n\n      fileIndex++\n    }\n    // walked off. no point continuing\n    return partial || null\n  }\n\n  #matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number,\n    // only match the file portions before this index\n    fileEnd: number = file.length,\n  ) {\n    let fi: number\n    let pi: number\n    let pl: number\n    let fl: number\n    for (\n      fi = fileIndex,\n        pi = patternIndex,\n        fl = Math.min(fileEnd, file.length),\n        pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      let p = pattern[pi]\n      let f = file[fi]\n\n      // should be impossible.\n      /* c8 ignore start */\n      if (p === false || p === GLOBSTAR) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into Matchers.\n      if (!portionMatch(p, f)) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though * can match \"\", except in\n    // partial mode, where it might simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  // Expand braces, except numeric ranges such as {0..999} with at\n  // least RANGE_MIN values. Each of those stays in its pattern as\n  // `0..999`, for the Matcher to test. If a range might\n  // be inside a [...] class, expand all of them instead.\n  #expandBraces(): string[] {\n    const { pattern } = this\n    if (this.options.nobrace) return this.braceExpand()\n    let code = 0xe000\n    while (pattern.includes(String.fromCharCode(code))) {\n      if (++code > 0xf8ff) return this.braceExpand()\n    }\n    const mark = String.fromCharCode(code)\n    let found = false\n    const marked = pattern.replace(\n      rangeRe,\n      (m, lo: string, hi: string) => {\n        const a = Number(lo)\n        const b = Number(hi)\n        if (\n          !Number.isSafeInteger(a) ||\n          !Number.isSafeInteger(b) ||\n          Math.abs(a - b) + 1 < RANGE_MIN\n        ) {\n          return m\n        }\n        found = true\n        return `${mark}${lo}..${hi}${mark}`\n      },\n    )\n    if (!found) return this.braceExpand()\n    const set = braceExpand(marked, this.options)\n    for (const p of set) {\n      for (const portion of p.split('/')) {\n        const c = portion.indexOf('[')\n        if (c !== -1 && c < portion.lastIndexOf(mark)) {\n          return this.braceExpand()\n        }\n        if (!this.options.noext && inRepeatOrNegExt(portion, mark)) {\n          return this.braceExpand()\n        }\n      }\n    }\n    this.#rangeMark = mark\n    return set\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    const {\n      nocase,\n      nocaseMagicOnly,\n      noext = false,\n      dot,\n      normalize,\n    } = options\n    const rangeMark = this.#rangeMark\n    const lit =\n      rangeMark && pattern.includes(rangeMark) ?\n        undefined\n      : literal(pattern, noext)\n    // in nocase mode, a literal with cased chars still needs a\n    // Matcher, unless nocaseMagicOnly is set.\n    if (\n      lit !== undefined &&\n      !(\n        nocase &&\n        !nocaseMagicOnly &&\n        pattern.toUpperCase() !== pattern.toLowerCase()\n      )\n    ) {\n      return this.#norm(lit)\n    }\n\n    if (this.#pending) return PENDING\n    let m = this.#matchers.get(pattern)\n    if (!m) {\n      if (!noext) assertValidExtglobs(pattern)\n      m = new Matcher(pattern, {\n        nocase,\n        noext,\n        dot,\n        normalize,\n        ...(rangeMark && { rangeMark }),\n      })\n      this.#matchers.set(pattern, m)\n    }\n    return m\n  }\n\n  #slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // treat the test path as a set of pathparts. If it was not just\n    // split or checked, check that it can match before splitting it.\n    let split = this.#cachedSplit(f)\n    if (!split) {\n      // the checks look at the path as given, so not if it is\n      // normalized\n      if (\n        !partial &&\n        !this.#form &&\n        (this.#endCheck || this.#literalCheck) &&\n        lastChecked !== f\n      ) {\n        lastChecked = f\n        const can = this.#canMatch(f)\n        if (can === 'no') return options.flipNegate ? false : this.negate\n        if (can === 'yes') return options.flipNegate ? true : !this.negate\n      }\n      split = this.#split(f)\n    }\n    const ff = split.parts\n    // the parts after level 2 resolves them, kept for the next pattern\n    // that tests the same path\n    const resolved =\n      this.#level2 ?\n        (split.resolved ??= this.#levelTwoFileOptimize(ff))\n      : ff\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let r = 0; r < set.length; r++) {\n      const pattern = set[r]!\n      const shape = partial ? undefined : this.#shapes[r]\n      // level 2 does not change a path of one portion\n      const hit =\n        shape === 'base' ?\n          portionMatch(pattern[0] as string | Matcher, filename)\n        : shape ? this.#matchShape(resolved, pattern, shape)\n        : options.matchBase && pattern.length === 1 ?\n          this.#matchRow([filename], [filename], pattern, partial)\n        : this.#matchRow(ff, resolved, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\nexport type { Form }\n/* c8 ignore stop */\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.d.ts.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.d.ts.map
index 09d6eab4e6502cde5495bf5ea51637d6db86999c..4894097546c9b5612a694256a79c2a39919f09af 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.d.ts.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;;;;;;;;GAkBG;AAEH,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,WAczE,CAAA"}
\ No newline at end of file
+{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;;;;;;;;;;;;;;GAkBG;AAEH,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,EACT,2CAGG,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,GAAG,eAAe,CAAM,KACvE,MAmBF,CAAA"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.js b/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.js
index 19ce86e7c86052265346584cd65e620cf2fcb377..3035d1ff79cc4a177f9155404317692ac127a882 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.js
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.js
@@ -18,6 +18,10 @@
  * unescaped.
  */
 export const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
+    // escape() writes a leading '!' as '@(!)' in windowsPathsNoEscape mode
+    if (windowsPathsNoEscape && s.startsWith('@(!)')) {
+        return ('!' + unescape(s.slice(4), { windowsPathsNoEscape, magicalBraces }));
+    }
     if (magicalBraces) {
         return windowsPathsNoEscape ?
             s.replace(/\[([^/\\])\]/g, '$1')
diff --git a/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.js.map b/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.js.map
index 6d507391171b5f7ccb04fd8da59e829d2715c260..87241df5d5a2c6cfbe86f94502f82893abfe286f 100644
--- a/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.js.map
+++ b/mac/patchers/desktop/node_modules/minimatch/dist/esm/unescape.js.map
@@ -1 +1 @@
-{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,IAAI,MACgD,EAAE,EACxE,EAAE;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;YAClC,CAAC,CAAC,CAAC;iBACE,OAAO,CAAC,0BAA0B,EAAE,MAAM,CAAC;iBAC3C,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,iBAAiB,EAAE,IAAI,CAAC;QACpC,CAAC,CAAC,CAAC;aACE,OAAO,CAAC,4BAA4B,EAAE,MAAM,CAAC;aAC7C,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = true,\n  }: Pick = {},\n) => {\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/\\[([^/\\\\])\\]/g, '$1')\n      : s\n          .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n          .replace(/\\\\([^/])/g, '$1')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n    : s\n        .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n        .replace(/\\\\([^/{}])/g, '$1')\n}\n"]}
\ No newline at end of file
+{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,EAC5B,aAAa,GAAG,IAAI,MACgD,EAAE,EAChE,EAAE;IACV,uEAAuE;IACvE,IAAI,oBAAoB,IAAI,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;QACjD,OAAO,CACL,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,oBAAoB,EAAE,aAAa,EAAE,CAAC,CACpE,CAAA;IACH,CAAC;IACD,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,oBAAoB,CAAC,CAAC;YACzB,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;YAClC,CAAC,CAAC,CAAC;iBACE,OAAO,CAAC,0BAA0B,EAAE,MAAM,CAAC;iBAC3C,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,oBAAoB,CAAC,CAAC;QACzB,CAAC,CAAC,OAAO,CAAC,iBAAiB,EAAE,IAAI,CAAC;QACpC,CAAC,CAAC,CAAC;aACE,OAAO,CAAC,4BAA4B,EAAE,MAAM,CAAC;aAC7C,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA","sourcesContent":["import type { MinimatchOptions } from './index.js'\n\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then\n * square-bracket escapes are removed, but not backslash escapes.\n *\n * For example, it will turn the string `'[*]'` into `*`, but it will not\n * turn `'\\\\*'` into `'*'`, because `\\` is a path separator in\n * `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n *\n * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be\n * unescaped.\n */\n\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n    magicalBraces = true,\n  }: Pick = {},\n): string => {\n  // escape() writes a leading '!' as '@(!)' in windowsPathsNoEscape mode\n  if (windowsPathsNoEscape && s.startsWith('@(!)')) {\n    return (\n      '!' + unescape(s.slice(4), { windowsPathsNoEscape, magicalBraces })\n    )\n  }\n  if (magicalBraces) {\n    return windowsPathsNoEscape ?\n        s.replace(/\\[([^/\\\\])\\]/g, '$1')\n      : s\n          .replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, '$1$2')\n          .replace(/\\\\([^/])/g, '$1')\n  }\n  return windowsPathsNoEscape ?\n      s.replace(/\\[([^/\\\\{}])\\]/g, '$1')\n    : s\n        .replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, '$1$2')\n        .replace(/\\\\([^/{}])/g, '$1')\n}\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/minimatch/package.json b/mac/patchers/desktop/node_modules/minimatch/package.json
index 75dee484979fb926cbd08ace62ec705458b94058..2425c0518733f106bd50cbb788794e00a76c4b25 100644
--- a/mac/patchers/desktop/node_modules/minimatch/package.json
+++ b/mac/patchers/desktop/node_modules/minimatch/package.json
@@ -2,10 +2,10 @@
   "author": "Isaac Z. Schlueter  (http://blog.izs.me)",
   "name": "minimatch",
   "description": "a glob matcher in javascript",
-  "version": "10.2.6",
+  "version": "11.0.9",
   "repository": {
     "type": "git",
-    "url": "git@github.com:isaacs/minimatch"
+    "url": "git+ssh://git@github.com/isaacs/minimatch.git"
   },
   "main": "./dist/commonjs/index.js",
   "types": "./dist/commonjs/index.d.ts",
@@ -27,8 +27,7 @@
   ],
   "scripts": {
     "preversion": "npm test",
-    "postversion": "npm publish",
-    "prepublishOnly": "git push origin --follow-tags",
+    "postversion": "git push origin --follow-tags",
     "prepare": "tshy",
     "pretest": "npm run prepare",
     "presnap": "npm run prepare",
@@ -42,12 +41,12 @@
     "postlint": "npm run format"
   },
   "engines": {
-    "node": "18 || 20 || >=22"
+    "node": "20 || >=22"
   },
   "devDependencies": {
-    "@types/node": "^26.1.2",
+    "@types/node": "^26.6.5",
     "mkdirp": "^3.0.1",
-    "oxlint": "^1.76.0",
+    "oxlint": "^1.90.0",
     "oxlint-tsgolint": "^7.0.2001",
     "prettier": "^3.9.6",
     "tap": "^21.7.5",
@@ -68,6 +67,7 @@
   "type": "module",
   "module": "./dist/esm/index.js",
   "dependencies": {
-    "brace-expansion": "^5.0.8"
+    "@isaacs/nonrecursive-glob-match": "^1.1.0",
+    "brace-expansion": "^5.0.12"
   }
 }
diff --git a/mac/patchers/desktop/node_modules/path-scurry/README.md b/mac/patchers/desktop/node_modules/path-scurry/README.md
index b5cb495c0bf3c8fca0063d58f2ec909356b2e470..eda036cbee49368b5da3737c1821340e1dcbc082 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/README.md
+++ b/mac/patchers/desktop/node_modules/path-scurry/README.md
@@ -236,7 +236,6 @@ constructor.
 - `fs` An object that will be used to override the default `fs`
   methods. Any methods that are not overridden will use Node's
   built-in implementations.
-
   - lstatSync
   - readdir (callback `withFileTypes` Dirent variant, used for
     readdirCB and most walks)
diff --git a/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.d.ts b/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.d.ts
index ef31b1b7716f6c9ae8127045dfa5cd87f6a076e3..a198a274fd5058093719166a47cd9726f5760088 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.d.ts
+++ b/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.d.ts
@@ -203,6 +203,13 @@ export declare abstract class PathBase implements Dirent {
     constructor(name: string, type: number | undefined, root: PathBase | undefined, roots: {
         [k: string]: PathBase;
     }, nocase: boolean, children: ChildrenCache, opts: PathOpts);
+    /**
+     * The file system methods that this Path uses, for a new root on
+     * another drive or UNC share.
+     *
+     * @internal
+     */
+    get fs(): FSOption;
     /**
      * Returns the depth of the Path object from its root.
      *
diff --git a/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.d.ts.map b/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.d.ts.map
index bf58a3a3ac71919dd09a2165ae355cef7cef57bc..c05ed0182e5590da385d0c9971fee90ce0e9f988 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.d.ts.map
+++ b/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAmBxC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE5C;;;;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,CAAA;CACrB,CAAA;AAED;;;;;GAKG;AACH,qBAAa,eAAgB,SAAQ,cAAc;IACjD;;OAEG;IACH,GAAG,EAAE,IAAI,CAAO;gBAGd,GAAG,GAAE,GAAG,GAAG,MAAsB,EACjC,IAAI,GAAE,cAAmB;IAc3B;;OAEG;IACH,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAOlC;;OAEG;IACH,OAAO,CAAC,EAAE,EAAE,OAAO;IAYnB;;OAEG;IACH,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;CAK/B;AAED;;;;;;GAMG;AACH,qBAAa,eAAgB,SAAQ,cAAc;IACjD;;OAEG;IACH,GAAG,EAAE,GAAG,CAAM;gBAEZ,GAAG,GAAE,GAAG,GAAG,MAAsB,EACjC,IAAI,GAAE,cAAmB;IAO3B;;OAEG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAInC;;OAEG;IACH,OAAO,CAAC,EAAE,EAAE,OAAO;IAYnB;;OAEG;IACH,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;CAG/B;AAED;;;;;;;GAOG;AACH,qBAAa,gBAAiB,SAAQ,eAAe;gBAEjD,GAAG,GAAE,GAAG,GAAG,MAAsB,EACjC,IAAI,GAAE,cAAmB;CAK5B;AAED;;;;GAIG;AACH,eAAO,MAAM,IAAI,qCAAuD,CAAA;AACxE,MAAM,MAAM,IAAI,GAAG,QAAQ,GAAG,YAAY,CAAC,OAAO,IAAI,CAAC,CAAA;AAEvD;;;;;GAKG;AACH,eAAO,MAAM,UAAU,EACnB,OAAO,eAAe,GACtB,OAAO,gBAAgB,GACvB,OAAO,eAGQ,CAAA;AACnB,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG,YAAY,CAAC,OAAO,UAAU,CAAC,CAAA"}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.js b/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.js
index 112f732d69a3f547755d47c441537f956bac3e71..2568de0e56079751357441e6c5584a4f3bdc7c51 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.js
+++ b/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.js
@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
 }) : function(o, v) {
     o["default"] = v;
 });
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
+var __importStar = (this && this.__importStar) || (function () {
+    var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function (o) {
+            var ar = [];
+            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+            return ar;
+        };
+        return ownKeys(o);
+    };
+    return function (mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+        __setModuleDefault(result, mod);
+        return result;
+    };
+})();
 Object.defineProperty(exports, "__esModule", { value: true });
 exports.PathScurry = exports.Path = exports.PathScurryDarwin = exports.PathScurryPosix = exports.PathScurryWin32 = exports.PathScurryBase = exports.PathPosix = exports.PathWin32 = exports.PathBase = exports.ChildrenCache = exports.ResolveCache = void 0;
 const lru_cache_1 = require("lru-cache");
@@ -55,14 +65,29 @@ const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOpti
         ...fsOption,
         promises: {
             ...defaultFS.promises,
-            ...(fsOption.promises || {}),
+            ...(fsOption.promises),
         },
     };
-// turn something like //?/c:/ into c:\
+// turn something like //?/c:/ into c:\, and //?/UNC/host/share/ or
+// //host/share into \\host\share\
 const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
-const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\');
+const uncLongRegexp = /^\\\\\?\\UNC\\([^\\]+\\[^\\]+)\\?$/i;
+const uncShareRegexp = /^\\\\[^\\?]+\\[^\\]+$/;
+const uncToDrive = (rootPath) => rootPath
+    .replace(/\//g, '\\')
+    .replace(uncDriveRegexp, '$1\\')
+    .replace(uncLongRegexp, '\\\\$1\\')
+    .replace(uncShareRegexp, '$&\\');
+// path.win32.parse() only finds the //?/UNC/ of a long UNC root
+const longUncRoot = /^[\\/]{2}\?[\\/]unc[\\/][^\\/]+[\\/][^\\/]+(?:[\\/]|$)/i;
+// //?/c:/x is the same path as c:/x
+const longDrivePrefix = /^[\\/]{2}\?[\\/](?=[a-z]:)/i;
+// //?/UNC/host/share/x is the same path as //host/share/x. This
+// matches up to the / after UNC, which with a \ in front of it is
+// the // in front of the host.
+const longUncPrefix = /^[\\/]{2}\?[\\/]unc(?=[\\/][^\\/]+[\\/][^\\/])/i;
 // windows paths are separated by either / or \
-const eitherSep = /[\\\/]/;
+const eitherSep = /[\\/]/;
 const UNKNOWN = 0; // may not even exist, for all we know
 const IFIFO = 0b0001;
 const IFCHR = 0b0010;
@@ -335,6 +360,15 @@ class PathBase {
             this.#fs = fsFromOption(opts.fs);
         }
     }
+    /**
+     * The file system methods that this Path uses, for a new root on
+     * another drive or UNC share.
+     *
+     * @internal
+     */
+    get fs() {
+        return this.#fs;
+    }
     /**
      * Returns the depth of the Path object from its root.
      *
@@ -1123,7 +1157,7 @@ class PathBase {
             const rp = await this.#fs.promises.realpath(this.fullpath());
             return (this.#realpath = this.resolve(rp));
         }
-        catch (_) {
+        catch {
             this.#markENOREALPATH();
         }
     }
@@ -1139,7 +1173,7 @@ class PathBase {
             const rp = this.#fs.realpathSync(this.fullpath());
             return (this.#realpath = this.resolve(rp));
         }
-        catch (_) {
+        catch {
             this.#markENOREALPATH();
         }
     }
@@ -1208,14 +1242,15 @@ class PathWin32 extends PathBase {
      * @internal
      */
     getRootString(path) {
-        return node_path_1.win32.parse(path).root;
+        return longUncRoot.exec(path)?.[0] ?? node_path_1.win32.parse(path).root;
     }
     /**
      * @internal
      */
     getRoot(rootPath) {
         rootPath = uncToDrive(rootPath.toUpperCase());
-        if (rootPath === this.root.name) {
+        // a root with no drive or UNC host is the root of this path
+        if (rootPath === this.root.name || /^[\\/]$/.test(rootPath)) {
             return this.root;
         }
         // ok, not that one, check if it matches another we know about
@@ -1225,7 +1260,10 @@ class PathWin32 extends PathBase {
             }
         }
         // otherwise, have to create a new one.
-        return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root);
+        return (this.roots[rootPath] = new PathScurryWin32(rootPath, {
+            nocase: this.nocase,
+            fs: this.fs,
+        }).root);
     }
     /**
      * @internal
@@ -1234,11 +1272,7 @@ class PathWin32 extends PathBase {
         // windows can (rarely) have case-sensitive filesystem, but
         // UNC and drive letters are always case-insensitive, and canonically
         // represented uppercase.
-        rootPath = rootPath
-            .toUpperCase()
-            .replace(/\//g, '\\')
-            .replace(uncDriveRegexp, '$1\\');
-        return rootPath === compare;
+        return uncToDrive(rootPath.toUpperCase()) === compare;
     }
 }
 exports.PathWin32 = PathWin32;
@@ -1919,6 +1953,10 @@ class PathScurryWin32 extends PathScurryBase {
     sep = '\\';
     constructor(cwd = process.cwd(), opts = {}) {
         const { nocase = true } = opts;
+        // use the same root as resolve() does for these paths
+        if (typeof cwd === 'string' && !cwd.startsWith('file://')) {
+            cwd = cwd.replace(longDrivePrefix, '').replace(longUncPrefix, '\\');
+        }
         super(cwd, node_path_1.win32, '\\', { ...opts, nocase });
         this.nocase = nocase;
         for (let p = this.cwd; p; p = p.parent) {
diff --git a/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.js.map b/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.js.map
index a20f78ada4d2a10d106003bc2d6dc4727f04899f..0fddaf553c1da7a49d1551b7704488e1b87d7dac 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.js.map
+++ b/mac/patchers/desktop/node_modules/path-scurry/dist/commonjs/index.js.map
@@ -1 +1 @@
-{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAAoC;AACpC,yCAAwC;AAExC,uCAAwC;AAExC,2BAMW;AACX,kDAAmC;AAEnC,MAAM,YAAY,GAAG,iBAAG,CAAC,MAAM,CAAA;AAC/B,yDAAyD;AACzD,8CAA8C;AAE9C,+CAAqE;AAErE,uCAAmC;AAqEnC,MAAM,SAAS,GAAY;IACzB,SAAS,EAAT,cAAS;IACT,OAAO,EAAE,YAAS;IAClB,WAAW,EAAX,gBAAW;IACX,YAAY,EAAZ,iBAAY;IACZ,YAAY;IACZ,QAAQ,EAAE;QACR,KAAK,EAAL,gBAAK;QACL,OAAO,EAAP,kBAAO;QACP,QAAQ,EAAR,mBAAQ;QACR,QAAQ,EAAR,mBAAQ;KACT;CACF,CAAA;AAED,0DAA0D;AAC1D,MAAM,YAAY,GAAG,CAAC,QAAmB,EAAW,EAAE,CACpD,CAAC,QAAQ,IAAI,QAAQ,KAAK,SAAS,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC;IAC5D,SAAS;IACX,CAAC,CAAC;QACE,GAAG,SAAS;QACZ,GAAG,QAAQ;QACX,QAAQ,EAAE;YACR,GAAG,SAAS,CAAC,QAAQ;YACrB,GAAG,CAAC,QAAQ,CAAC,QAAQ,IAAI,EAAE,CAAC;SAC7B;KACF,CAAA;AAEL,uCAAuC;AACvC,MAAM,cAAc,GAAG,wBAAwB,CAAA;AAC/C,MAAM,UAAU,GAAG,CAAC,QAAgB,EAAU,EAAE,CAC9C,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AAE/D,+CAA+C;AAC/C,MAAM,SAAS,GAAG,QAAQ,CAAA;AAE1B,MAAM,O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,GAAG,CAAC,CAAA;IAC1B,CAAC;CACF;AA1CD,0CA0CC;AAED;;;;;;;GAOG;AACH,MAAa,gBAAiB,SAAQ,eAAe;IACnD,YACE,MAAoB,OAAO,CAAC,GAAG,EAAE,EACjC,OAAuB,EAAE;QAEzB,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,IAAI,CAAA;QAC9B,KAAK,CAAC,GAAG,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;IACjC,CAAC;CACF;AARD,4CAQC;AAED;;;;GAIG;AACU,QAAA,IAAI,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAA;AAGxE;;;;;GAKG;AACU,QAAA,UAAU,GAIrB,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,eAAe;IAC9C,CAAC,CAAC,OAAO,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB;QAClD,CAAC,CAAC,eAAe,CAAA","sourcesContent":["import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises || {}),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n  rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new LRUCache({ max: 2 ** 12 })\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new LRUCache({ max: 2 ** 12 })\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /* c8 ignore start */\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   *\n   * @deprecated\n   */\n  get path(): string {\n    return this.parentPath\n  }\n  /* c8 ignore stop */\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    if (rootPath === this.root.name) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(\n      rootPath,\n      this,\n    ).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    rootPath = rootPath\n      .toUpperCase()\n      .replace(/\\//g, '\\\\')\n      .replace(uncDriveRegexp, '$1\\\\')\n    return rootPath === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n"]}
\ No newline at end of file
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src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C,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB;QAClD,CAAC,CAAC,eAAe,CAAA","sourcesContent":["import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\, and //?/UNC/host/share/ or\n// //host/share into \\\\host\\share\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncLongRegexp = /^\\\\\\\\\\?\\\\UNC\\\\([^\\\\]+\\\\[^\\\\]+)\\\\?$/i\nconst uncShareRegexp = /^\\\\\\\\[^\\\\?]+\\\\[^\\\\]+$/\nconst uncToDrive = (rootPath: string): string =>\n  rootPath\n    .replace(/\\//g, '\\\\')\n    .replace(uncDriveRegexp, '$1\\\\')\n    .replace(uncLongRegexp, '\\\\\\\\$1\\\\')\n    .replace(uncShareRegexp, '$&\\\\')\n\n// path.win32.parse() only finds the //?/UNC/ of a long UNC root\nconst longUncRoot =\n  /^[\\\\/]{2}\\?[\\\\/]unc[\\\\/][^\\\\/]+[\\\\/][^\\\\/]+(?:[\\\\/]|$)/i\n\n// //?/c:/x is the same path as c:/x\nconst longDrivePrefix = /^[\\\\/]{2}\\?[\\\\/](?=[a-z]:)/i\n// //?/UNC/host/share/x is the same path as //host/share/x. This\n// matches up to the / after UNC, which with a \\ in front of it is\n// the // in front of the host.\nconst longUncPrefix = /^[\\\\/]{2}\\?[\\\\/]unc(?=[\\\\/][^\\\\/]+[\\\\/][^\\\\/])/i\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new LRUCache({ max: 2 ** 12 })\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new LRUCache({ max: 2 ** 12 })\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /* c8 ignore start */\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   *\n   * @deprecated\n   */\n  get path(): string {\n    return this.parentPath\n  }\n  /* c8 ignore stop */\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * The file system methods that this Path uses, for a new root on\n   * another drive or UNC share.\n   *\n   * @internal\n   */\n  get fs(): FSOption {\n    return this.#fs\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return longUncRoot.exec(path)?.[0] ?? win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    // a root with no drive or UNC host is the root of this path\n    if (rootPath === this.root.name || /^[\\\\/]$/.test(rootPath)) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(rootPath, {\n      nocase: this.nocase,\n      fs: this.fs,\n    }).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    return uncToDrive(rootPath.toUpperCase()) === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    // use the same root as resolve() does for these paths\n    if (typeof cwd === 'string' && !cwd.startsWith('file://')) {\n      cwd = cwd.replace(longDrivePrefix, '').replace(longUncPrefix, '\\\\')\n    }\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.d.ts b/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.d.ts
index ef31b1b7716f6c9ae8127045dfa5cd87f6a076e3..a198a274fd5058093719166a47cd9726f5760088 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.d.ts
+++ b/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.d.ts
@@ -203,6 +203,13 @@ export declare abstract class PathBase implements Dirent {
     constructor(name: string, type: number | undefined, root: PathBase | undefined, roots: {
         [k: string]: PathBase;
     }, nocase: boolean, children: ChildrenCache, opts: PathOpts);
+    /**
+     * The file system methods that this Path uses, for a new root on
+     * another drive or UNC share.
+     *
+     * @internal
+     */
+    get fs(): FSOption;
     /**
      * Returns the depth of the Path object from its root.
      *
diff --git a/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.d.ts.map b/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.d.ts.map
index bf58a3a3ac71919dd09a2165ae355cef7cef57bc..c05ed0182e5590da385d0c9971fee90ce0e9f988 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.d.ts.map
+++ b/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.d.ts.map
@@ -1 +1 @@
-{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAmBxC,OAAO,EAAE,QAAQ,EAA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end of file
diff --git a/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.js b/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.js
index dc7cae493aa50fbad6c60904329e97c1f279ddd6..9f08dd871504dbf44419cfabedaabd894603d5dd 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.js
+++ b/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.js
@@ -29,14 +29,29 @@ const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOpti
         ...fsOption,
         promises: {
             ...defaultFS.promises,
-            ...(fsOption.promises || {}),
+            ...(fsOption.promises),
         },
     };
-// turn something like //?/c:/ into c:\
+// turn something like //?/c:/ into c:\, and //?/UNC/host/share/ or
+// //host/share into \\host\share\
 const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
-const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\');
+const uncLongRegexp = /^\\\\\?\\UNC\\([^\\]+\\[^\\]+)\\?$/i;
+const uncShareRegexp = /^\\\\[^\\?]+\\[^\\]+$/;
+const uncToDrive = (rootPath) => rootPath
+    .replace(/\//g, '\\')
+    .replace(uncDriveRegexp, '$1\\')
+    .replace(uncLongRegexp, '\\\\$1\\')
+    .replace(uncShareRegexp, '$&\\');
+// path.win32.parse() only finds the //?/UNC/ of a long UNC root
+const longUncRoot = /^[\\/]{2}\?[\\/]unc[\\/][^\\/]+[\\/][^\\/]+(?:[\\/]|$)/i;
+// //?/c:/x is the same path as c:/x
+const longDrivePrefix = /^[\\/]{2}\?[\\/](?=[a-z]:)/i;
+// //?/UNC/host/share/x is the same path as //host/share/x. This
+// matches up to the / after UNC, which with a \ in front of it is
+// the // in front of the host.
+const longUncPrefix = /^[\\/]{2}\?[\\/]unc(?=[\\/][^\\/]+[\\/][^\\/])/i;
 // windows paths are separated by either / or \
-const eitherSep = /[\\\/]/;
+const eitherSep = /[\\/]/;
 const UNKNOWN = 0; // may not even exist, for all we know
 const IFIFO = 0b0001;
 const IFCHR = 0b0010;
@@ -307,6 +322,15 @@ export class PathBase {
             this.#fs = fsFromOption(opts.fs);
         }
     }
+    /**
+     * The file system methods that this Path uses, for a new root on
+     * another drive or UNC share.
+     *
+     * @internal
+     */
+    get fs() {
+        return this.#fs;
+    }
     /**
      * Returns the depth of the Path object from its root.
      *
@@ -1095,7 +1119,7 @@ export class PathBase {
             const rp = await this.#fs.promises.realpath(this.fullpath());
             return (this.#realpath = this.resolve(rp));
         }
-        catch (_) {
+        catch {
             this.#markENOREALPATH();
         }
     }
@@ -1111,7 +1135,7 @@ export class PathBase {
             const rp = this.#fs.realpathSync(this.fullpath());
             return (this.#realpath = this.resolve(rp));
         }
-        catch (_) {
+        catch {
             this.#markENOREALPATH();
         }
     }
@@ -1179,14 +1203,15 @@ export class PathWin32 extends PathBase {
      * @internal
      */
     getRootString(path) {
-        return win32.parse(path).root;
+        return longUncRoot.exec(path)?.[0] ?? win32.parse(path).root;
     }
     /**
      * @internal
      */
     getRoot(rootPath) {
         rootPath = uncToDrive(rootPath.toUpperCase());
-        if (rootPath === this.root.name) {
+        // a root with no drive or UNC host is the root of this path
+        if (rootPath === this.root.name || /^[\\/]$/.test(rootPath)) {
             return this.root;
         }
         // ok, not that one, check if it matches another we know about
@@ -1196,7 +1221,10 @@ export class PathWin32 extends PathBase {
             }
         }
         // otherwise, have to create a new one.
-        return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root);
+        return (this.roots[rootPath] = new PathScurryWin32(rootPath, {
+            nocase: this.nocase,
+            fs: this.fs,
+        }).root);
     }
     /**
      * @internal
@@ -1205,11 +1233,7 @@ export class PathWin32 extends PathBase {
         // windows can (rarely) have case-sensitive filesystem, but
         // UNC and drive letters are always case-insensitive, and canonically
         // represented uppercase.
-        rootPath = rootPath
-            .toUpperCase()
-            .replace(/\//g, '\\')
-            .replace(uncDriveRegexp, '$1\\');
-        return rootPath === compare;
+        return uncToDrive(rootPath.toUpperCase()) === compare;
     }
 }
 /**
@@ -1887,6 +1911,10 @@ export class PathScurryWin32 extends PathScurryBase {
     sep = '\\';
     constructor(cwd = process.cwd(), opts = {}) {
         const { nocase = true } = opts;
+        // use the same root as resolve() does for these paths
+        if (typeof cwd === 'string' && !cwd.startsWith('file://')) {
+            cwd = cwd.replace(longDrivePrefix, '').replace(longUncPrefix, '\\');
+        }
         super(cwd, win32, '\\', { ...opts, nocase });
         this.nocase = nocase;
         for (let p = this.cwd; p; p = p.parent) {
diff --git a/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.js.map b/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.js.map
index 51e56ee11f6287f5f5c183589ab4b4f2826ada70..d2ddbf6230d7f3b608c2d2d01901223e9c8952b6 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.js.map
+++ b/mac/patchers/desktop/node_modules/path-scurry/dist/esm/index.js.map
@@ -1 +1 @@
-{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAExC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,OAAO,EACL,SAAS,EACT,OAAO,IAAI,SAAS,EACpB,WAAW,EACX,YAAY,EACZ,YAAY,IAAI,GAAG,GACpB,MAAM,IAAI,CAAA;AACX,OAAO,KAAK,QAAQ,MAAM,SAAS,CAAA;AAEnC,MAAM,YAAY,GAAG,GAAG,CAAC,MAAM,CAAA;AAC/B,yDAAyD;AACzD,8CAA8C;AAE9C,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAErE,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAqEnC,MAAM,SAAS,GAAY;IACzB,SAAS;IACT,OAAO,EAAE,SAAS;IAClB,W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AAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB;QAClD,CAAC,CAAC,eAAe,CAAA","sourcesContent":["import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises || {}),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n  rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new LRUCache({ max: 2 ** 12 })\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new LRUCache({ max: 2 ** 12 })\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /* c8 ignore start */\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   *\n   * @deprecated\n   */\n  get path(): string {\n    return this.parentPath\n  }\n  /* c8 ignore stop */\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    if (rootPath === this.root.name) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(\n      rootPath,\n      this,\n    ).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    rootPath = rootPath\n      .toUpperCase()\n      .replace(/\\//g, '\\\\')\n      .replace(uncDriveRegexp, '$1\\\\')\n    return rootPath === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n"]}
\ No newline at end of file
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAExC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,OAAO,EACL,SAAS,EACT,OAAO,IAAI,SAAS,EACpB,WAAW,EACX,YAAY,EACZ,YAAY,IAAI,GAAG,GACpB,MAAM,IAAI,CAAA;AACX,OAAO,KAAK,QAAQ,MAAM,SAAS,CAAA;AAEnC,MAAM,YAAY,GAAG,GAAG,CAAC,MAAM,CAAA;AAC/B,yDAAyD;AACzD,8CAA8C;AAE9C,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAErE,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAqEnC,MAAM,SAAS,GAAY;IACz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EACL,SAAS,EACT,IAAI,CAAC,KAAK,EACV,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,aAAa,EAAE,EACpB,EAAE,EAAE,EAAE,CACP,CAAA;IACH,CAAC;IAED;;OAEG;IACH,UAAU,CAAC,CAAS;QAClB,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;IAC1B,CAAC;CACF;AAED;;;;;;;GAOG;AACH,MAAM,OAAO,gBAAiB,SAAQ,eAAe;IACnD,YACE,MAAoB,OAAO,CAAC,GAAG,EAAE,EACjC,OAAuB,EAAE;QAEzB,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,IAAI,CAAA;QAC9B,KAAK,CAAC,GAAG,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;IACjC,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAA;AAGxE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,UAAU,GAIrB,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,eAAe;IAC9C,CAAC,CAAC,OAAO,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB;QAClD,CAAC,CAAC,eAAe,CAAA","sourcesContent":["import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\, and //?/UNC/host/share/ or\n// //host/share into \\\\host\\share\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncLongRegexp = /^\\\\\\\\\\?\\\\UNC\\\\([^\\\\]+\\\\[^\\\\]+)\\\\?$/i\nconst uncShareRegexp = /^\\\\\\\\[^\\\\?]+\\\\[^\\\\]+$/\nconst uncToDrive = (rootPath: string): string =>\n  rootPath\n    .replace(/\\//g, '\\\\')\n    .replace(uncDriveRegexp, '$1\\\\')\n    .replace(uncLongRegexp, '\\\\\\\\$1\\\\')\n    .replace(uncShareRegexp, '$&\\\\')\n\n// path.win32.parse() only finds the //?/UNC/ of a long UNC root\nconst longUncRoot =\n  /^[\\\\/]{2}\\?[\\\\/]unc[\\\\/][^\\\\/]+[\\\\/][^\\\\/]+(?:[\\\\/]|$)/i\n\n// //?/c:/x is the same path as c:/x\nconst longDrivePrefix = /^[\\\\/]{2}\\?[\\\\/](?=[a-z]:)/i\n// //?/UNC/host/share/x is the same path as //host/share/x. This\n// matches up to the / after UNC, which with a \\ in front of it is\n// the // in front of the host.\nconst longUncPrefix = /^[\\\\/]{2}\\?[\\\\/]unc(?=[\\\\/][^\\\\/]+[\\\\/][^\\\\/])/i\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new LRUCache({ max: 2 ** 12 })\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new LRUCache({ max: 2 ** 12 })\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /* c8 ignore start */\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   *\n   * @deprecated\n   */\n  get path(): string {\n    return this.parentPath\n  }\n  /* c8 ignore stop */\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * The file system methods that this Path uses, for a new root on\n   * another drive or UNC share.\n   *\n   * @internal\n   */\n  get fs(): FSOption {\n    return this.#fs\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return longUncRoot.exec(path)?.[0] ?? win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    // a root with no drive or UNC host is the root of this path\n    if (rootPath === this.root.name || /^[\\\\/]$/.test(rootPath)) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(rootPath, {\n      nocase: this.nocase,\n      fs: this.fs,\n    }).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    return uncToDrive(rootPath.toUpperCase()) === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    // use the same root as resolve() does for these paths\n    if (typeof cwd === 'string' && !cwd.startsWith('file://')) {\n      cwd = cwd.replace(longDrivePrefix, '').replace(longUncPrefix, '\\\\')\n    }\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n"]}
\ No newline at end of file
diff --git a/mac/patchers/desktop/node_modules/path-scurry/package.json b/mac/patchers/desktop/node_modules/path-scurry/package.json
index 68123fb70f16be142f3478bb81d5928a3035b99c..2cc1706804ab3658d4ef099d73838c1ca6897a77 100644
--- a/mac/patchers/desktop/node_modules/path-scurry/package.json
+++ b/mac/patchers/desktop/node_modules/path-scurry/package.json
@@ -1,6 +1,6 @@
 {
   "name": "path-scurry",
-  "version": "2.0.2",
+  "version": "3.0.0",
   "description": "walk paths fast and efficiently",
   "author": "Isaac Z. Schlueter  (https://blog.izs.me)",
   "main": "./dist/commonjs/index.js",
@@ -31,7 +31,7 @@
     "presnap": "npm run prepare",
     "test": "tap",
     "snap": "tap",
-    "format": "prettier --write . --log-level warn",
+    "format": "prettier --write .",
     "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts",
     "bench": "bash ./scripts/bench.sh"
   },
@@ -41,9 +41,9 @@
     "mkdirp": "^3.0.0",
     "prettier": "^3.3.2",
     "rimraf": "^6.1.3",
-    "tap": "^21.6.1",
+    "tap": "^21.8.0",
     "ts-node": "^10.9.2",
-    "tshy": "^3.3.2",
+    "tshy": "^4.1.3",
     "typedoc": "^0.28.17"
   },
   "engines": {
diff --git a/mac/patchers/desktop/package-lock.json b/mac/patchers/desktop/package-lock.json
index 3558f06823bdd18a4850b64078247dc096d32f46..d3a777258cfd1d62af5747d735e5766148cf1198 100644
--- a/mac/patchers/desktop/package-lock.json
+++ b/mac/patchers/desktop/package-lock.json
@@ -6,20 +6,20 @@
     "": {
       "name": "grokbot-desktop-patcher",
       "dependencies": {
-        "@electron/asar": "4.3.1"
+        "@electron/asar": "4.3.2"
       },
       "engines": {
         "node": ">=22.12"
       }
     },
     "node_modules/@electron/asar": {
-      "version": "4.3.1",
-      "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-4.3.1.tgz",
-      "integrity": "sha512-6pI64z/tMSBkUTZLQFYhs2YiB7fS9sKA6gy7/2nH1Ju7GGwT32UPsj4Mxsws5NMmtR6C0zYdXVxEU/rGqJRCJA==",
+      "version": "4.3.2",
+      "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-4.3.2.tgz",
+      "integrity": "sha512-2nwyO3OgmLgkYQe6TzB8FmyrBKGgmXzSO51ozoG2BpHOLPTPdQpBt/zD0MdPkhQr4UqVgw3u09y4uYxgZKhmtg==",
       "license": "MIT",
       "dependencies": {
-        "glob": "^13.0.2",
-        "minimatch": "^10.0.1"
+        "glob": "^14.0.2",
+        "minimatch": "^11.0.1"
       },
       "bin": {
         "asar": "bin/asar.mjs"
@@ -28,6 +28,12 @@
         "node": ">=22.12.0"
       }
     },
+    "node_modules/@isaacs/nonrecursive-glob-match": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
+      "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
+      "license": "BlueOak-1.0.0"
+    },
     "node_modules/balanced-match": {
       "version": "4.0.4",
       "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
@@ -38,9 +44,9 @@
       }
     },
     "node_modules/brace-expansion": {
-      "version": "5.0.12",
-      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
-      "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
+      "version": "5.0.13",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz",
+      "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==",
       "license": "MIT",
       "dependencies": {
         "balanced-match": "^4.0.2"
@@ -50,14 +56,14 @@
       }
     },
     "node_modules/glob": {
-      "version": "13.0.6",
-      "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
-      "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
+      "version": "14.0.6",
+      "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz",
+      "integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==",
       "license": "BlueOak-1.0.0",
       "dependencies": {
-        "minimatch": "^10.2.2",
+        "minimatch": "^11.0.5",
         "minipass": "^7.1.3",
-        "path-scurry": "^2.0.2"
+        "path-scurry": "^3.0.0"
       },
       "engines": {
         "node": "18 || 20 || >=22"
@@ -76,15 +82,16 @@
       }
     },
     "node_modules/minimatch": {
-      "version": "10.2.6",
-      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
-      "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
+      "version": "11.0.9",
+      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
+      "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
       "license": "BlueOak-1.0.0",
       "dependencies": {
-        "brace-expansion": "^5.0.8"
+        "@isaacs/nonrecursive-glob-match": "^1.1.0",
+        "brace-expansion": "^5.0.12"
       },
       "engines": {
-        "node": "18 || 20 || >=22"
+        "node": "20 || >=22"
       },
       "funding": {
         "url": "https://github.com/sponsors/isaacs"
@@ -100,9 +107,9 @@
       }
     },
     "node_modules/path-scurry": {
-      "version": "2.0.2",
-      "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
-      "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz",
+      "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==",
       "license": "BlueOak-1.0.0",
       "dependencies": {
         "lru-cache": "^11.0.0",
diff --git a/mac/patchers/desktop/package.json b/mac/patchers/desktop/package.json
index da887bdb57a737a8f0392a7231d7f4de780e6e7f..56ade2caef1d5c846756a55c36ed503435a93b7b 100644
--- a/mac/patchers/desktop/package.json
+++ b/mac/patchers/desktop/package.json
@@ -1 +1 @@
-{"name":"grokbot-desktop-patcher","private":true,"type":"module","engines":{"node":">=22.12"},"dependencies":{"@electron/asar":"4.3.1"}}
+{"name":"grokbot-desktop-patcher","private":true,"type":"module","engines":{"node":">=22.12"},"dependencies":{"@electron/asar":"4.3.2"}}
\ No newline at end of file
diff --git a/mac/patchers/desktop/patch.mjs b/mac/patchers/desktop/patch.mjs
index 0a31261997026623ca07c077e396bf52b46e8fb6..fcfb618c0a626c984c7f565d88eef7b8d6976957 100644
--- a/mac/patchers/desktop/patch.mjs
+++ b/mac/patchers/desktop/patch.mjs
@@ -13,13 +13,16 @@ import { acquireDesktopSource } from './download-original.mjs';
 
 const here = path.dirname(fileURLToPath(import.meta.url));
 const root = path.resolve(here, '../..');
-const supported = JSON.parse(await readFile(path.join(here, 'supported.json')));
+// Apple silicon inputs live here; the Intel build of the same version has its own pins and
+// recipes (ported with windows/tools/port-desktop-recipes.mjs --platform mac) under x64/.
+const inputDirectories = { arm64: here, x64: path.join(here, 'x64') };
+const tailcatBinaries = { arm64: 'dist/network/grokbot-tailcat', x64: 'dist/network/x64/grokbot-tailcat' };
 const startedAt = performance.now();
 const timings = {};
 const args = process.argv.slice(2);
 const arg = name => { const index = args.indexOf(name); return index >= 0 ? args[index + 1] : null; };
 if (args.includes('--help')) {
-  console.log('node patchers/desktop/patch.mjs [--source <原版.app或.dmg>] [--output <新.app>] [--backup <原版备份.app>] [--identity ] [--verify-only]\n省略 --source 时自动下载指定版本原版。');
+  console.log('node patchers/desktop/patch.mjs [--arch ] [--source <原版.app或.dmg>] [--output <新.app>] [--backup <原版备份.app>] [--identity ] [--verify-only]\n省略 --source 时自动下载指定版本原版;省略 --arch 时按本机芯片选择(Apple 芯片 arm64,Intel x64)。');
   process.exit(0);
 }
 if (process.platform !== 'darwin') throw new Error('macOS App 构建与签名必须在 macOS 上进行。');
@@ -32,6 +35,20 @@ const sha = bytes => createHash('sha256').update(bytes).digest('hex');
 const hash = async filename => sha(await readFile(filename));
 const exists = async filename => { try { await stat(filename); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } };
 const run = (command, argv, options = {}) => execFileSync(command, argv, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], ...options });
+// hw.optional.arm64 is 1 on Apple silicon even when Node itself runs under Rosetta.
+const machineArch = () => { try { return run('sysctl', ['-n', 'hw.optional.arm64']).trim() === '1' ? 'arm64' : 'x64'; } catch { return 'x64'; } };
+// A given DMG names its own build; download-original.mjs then checks its full digest.
+async function sourceArch(source) {
+  if (!source || path.extname(source).toLowerCase() !== '.dmg') return null;
+  const { size } = await stat(path.resolve(source));
+  for (const [name, directory] of Object.entries(inputDirectories))
+    if (JSON.parse(await readFile(path.join(directory, 'supported.json'))).archive.bytes === size) return name;
+  return null;
+}
+const arch = arg('--arch') ?? await sourceArch(arg('--source')) ?? machineArch();
+if (!Object.hasOwn(inputDirectories, arch)) throw new Error('--arch 只能是 arm64 或 x64。');
+const inputs = inputDirectories[arch];
+const supported = JSON.parse(await readFile(path.join(inputs, 'supported.json')));
 const plist = filename => JSON.parse(run('plutil', ['-convert', 'json', '-o', '-', filename]));
 const writePlist = async (filename, value) => { await writeFile(filename, JSON.stringify(value)); run('plutil', ['-convert', 'xml1', filename]); };
 async function nativeFiles(directory) {
@@ -70,6 +87,7 @@ try {
     app = path.join(mount, 'Grok Bot.app');
   }
   if (!app.endsWith('.app')) throw new Error('输入必须是原版 Grok Bot.app 或 DMG。');
+  run('codesign', ['--verify', '--deep', '--strict', app]);
   const infoPath = path.join(app, 'Contents/Info.plist');
   const info = plist(infoPath);
   const asarPath = path.join(app, 'Contents/Resources/app.asar');
@@ -77,8 +95,18 @@ try {
   const [asarSha256, frameworkSha256] = await Promise.all([hash(asarPath), hash(path.join(app, frameworkRelative))]);
   if (info.CFBundleIdentifier !== supported.bundleId || info.CFBundleShortVersionString !== supported.version ||
       asarSha256 !== supported.asarSha256 || frameworkSha256 !== supported.frameworkSha256)
-    throw new Error(`不支持此发行包。仅支持未经修改的 Grok Bot ${supported.version} macOS ${supported.architecture};版本、ASAR 或 Electron Framework 摘要不匹配。`);
-  console.log(JSON.stringify({ verified: true, version: supported.version, architecture: supported.architecture, asarSha256 }));
+    throw new Error(`不支持此发行包。仅支持未经修改的 Grok Bot ${supported.version} macOS ${supported.architecture};版本、ASAR 或 Electron Framework 摘要不匹配。另一种芯片的原版请加 --arch ${arch === 'arm64' ? 'x64' : 'arm64'}。`);
+  const asar = createRequire(import.meta.url)('@electron/asar');
+  const unpacked = path.join(temporary, 'app');
+  asar.extractAll(asarPath, unpacked);
+  const notificationPolicy = await extractNotificationPolicy(unpacked, inputs);
+  const pkgPath = path.join(unpacked, 'package.json');
+  const pkg = JSON.parse(await readFile(pkgPath));
+  if (pkg.version !== supported.version) throw new Error('ASAR 包版本不一致。');
+  const patchStarted = performance.now();
+  await applyReleaseRecipes(unpacked, path.join(inputs, 'recipes'));
+  timings.patchSeconds = Number(((performance.now() - patchStarted) / 1000).toFixed(3));
+  console.log(JSON.stringify({ verified: true, recipesVerified: true, version: supported.version, architecture: supported.architecture, asarSha256 }));
   if (!args.includes('--verify-only')) {
     if (await exists(output)) throw new Error(`输出已存在,不会覆盖:${output}`);
     if (output === backup || output.startsWith(`${backup}/`) || backup.startsWith(`${output}/`)) throw new Error('输出与备份路径必须独立。');
@@ -92,32 +120,16 @@ try {
     }
     await mkdir(path.dirname(output), { recursive: true });
     run('ditto', [app, output]); createdOutput = true;
-    let asar;
-    try { asar = createRequire(import.meta.url)('@electron/asar'); }
-    catch { try { asar = createRequire(path.join(root, 'desktop/package.json'))('@electron/asar'); }
-      catch { throw new Error('缺少 @electron/asar;执行 npm install --prefix patchers/desktop。'); } }
-    const unpacked = path.join(temporary, 'app');
-    asar.extractAll(asarPath, unpacked);
-    const notificationPolicy = await extractNotificationPolicy(unpacked, here);
-    const pkgPath = path.join(unpacked, 'package.json');
-    const pkg = JSON.parse(await readFile(pkgPath));
-    if (pkg.version !== supported.version) throw new Error('ASAR 包版本不一致。');
     const previousMain = pkg.main;
     pkg.main = 'local-client/main.mjs';
     await writeFile(pkgPath, JSON.stringify(pkg, null, 2));
     await cp(path.join(root, 'clients/desktop'), path.join(unpacked, 'local-client'), { recursive: true, filter: filename => !filename.endsWith('/notification-policy.mjs') });
     await writeFile(path.join(unpacked, 'local-client/notification-policy.mjs'), notificationPolicy);
     await cp(path.join(root, 'clients/shared'), path.join(unpacked, 'shared'), { recursive: true });
-    await cp(path.join(root, 'dist/network/grokbot-tailcat'), path.join(output, 'Contents/Resources/grokbot-tailcat'));
+    await cp(path.join(root, tailcatBinaries[arch]), path.join(output, 'Contents/Resources/grokbot-tailcat'));
+    // Copies made on Windows or extracted from some archives lose the executable bit.
+    await chmod(path.join(output, 'Contents/Resources/grokbot-tailcat'), 0o755);
     await cp(path.join(root, 'network/TAILCAT-LICENSE'), path.join(output, 'Contents/Resources/TAILCAT-LICENSE'));
-    const patchStarted = performance.now();
-    if (await exists(path.join(here, 'recipes/manifest.json'))) {
-      await applyReleaseRecipes(unpacked, path.join(here, 'recipes'));
-    } else {
-      const { patchDesktopPayload } = await import('./prepare-payload.mjs');
-      await patchDesktopPayload(unpacked, path.join(root, 'clients/desktop'));
-    }
-    timings.patchSeconds = Number(((performance.now() - patchStarted) / 1000).toFixed(3));
     // ASAR extraction does not retain Unix executable bits for native helpers.
     for (const name of ['sand-op-launcher', 'sand-webauthn-signer'])
       await chmod(path.join(unpacked, 'dist/native', name), 0o755);
diff --git a/mac/patchers/desktop/x64/notification-policy.json b/mac/patchers/desktop/x64/notification-policy.json
new file mode 100644
index 0000000000000000000000000000000000000000..48e27d2b3ac500a6f39681d13f5c32ba26cf0a4f
--- /dev/null
+++ b/mac/patchers/desktop/x64/notification-policy.json
@@ -0,0 +1,7 @@
+{
+  "source": "dist/electron-main/main-app.cjs",
+  "sourceSha256": "deed55b7f530d9b745fffe3ce944e228a72b807e5667a4989a363d740ba68ebf",
+  "sha256": "3be4aafc23abfb00989607b8acbb91b60c9e5c90c1877f0a3bffce8c7b1a8bbd",
+  "byteOffset": 2409633,
+  "byteLength": 4070
+}
diff --git a/mac/patchers/desktop/x64/recipes/000.gbp.gz b/mac/patchers/desktop/x64/recipes/000.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..33391de0252ef6cd94dfc4a4e778bfb82441d3b4
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/000.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/001.gbp.gz b/mac/patchers/desktop/x64/recipes/001.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..04ca9ab68a16662befc89901b7f228a1bb4cb3df
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/001.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/002.gbp.gz b/mac/patchers/desktop/x64/recipes/002.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..1fe84512fa40beca25805b3c0e03eb36c61cf377
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/002.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/003.gbp.gz b/mac/patchers/desktop/x64/recipes/003.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..dc49432dd27c42ffd30c60618c9732297a880eba
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/003.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/004.gbp.gz b/mac/patchers/desktop/x64/recipes/004.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..2e62d6a6a3d8b1b2752dd1735bc1dbfbe0a4307f
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/004.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/005.gbp.gz b/mac/patchers/desktop/x64/recipes/005.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..c1e2bfb050e0fa2a23a766113f17eecce92305ba
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/005.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/006.gbp.gz b/mac/patchers/desktop/x64/recipes/006.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..d97a14e2404b0e709ee663ab663c1ce91cd69fb6
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/006.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/007.gbp.gz b/mac/patchers/desktop/x64/recipes/007.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..b243caeb7b65bd4308f01b46f45bec5a674052fc
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/007.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/008.gbp.gz b/mac/patchers/desktop/x64/recipes/008.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..99223924c3c4f1e04d591c55cd9654334b741704
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/008.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/009.gbp.gz b/mac/patchers/desktop/x64/recipes/009.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..1d2449c8b16795f94765dcea963712d3d8f14c45
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/009.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/010.gbp.gz b/mac/patchers/desktop/x64/recipes/010.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..51a0698999f6347bbef986d72bc009d6c0b680a2
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/010.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/011.gbp.gz b/mac/patchers/desktop/x64/recipes/011.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..883c37a9d2b855ea6c5f043504a7bd1c69450e2c
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/011.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/012.gbp.gz b/mac/patchers/desktop/x64/recipes/012.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..4a1b9a8b81b761c7b0d9f50c2b16ca70e2ad9b7d
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/012.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/013.gbp.gz b/mac/patchers/desktop/x64/recipes/013.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..b0e241af7623e065919d82a529aac4b97aeaf60a
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/013.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/014.gbp.gz b/mac/patchers/desktop/x64/recipes/014.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..a37e47495e25ce5d3b0d768f0617fd5f7ae53867
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/014.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/015.gbp.gz b/mac/patchers/desktop/x64/recipes/015.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..da0ab8205f8c365cd3b76be5f7c1f60499125ae3
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/015.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/016.gbp.gz b/mac/patchers/desktop/x64/recipes/016.gbp.gz
new file mode 100644
index 0000000000000000000000000000000000000000..d794a58f955d0aaddd70bbb90d92945ced3f5bb1
Binary files /dev/null and b/mac/patchers/desktop/x64/recipes/016.gbp.gz differ
diff --git a/mac/patchers/desktop/x64/recipes/manifest.json b/mac/patchers/desktop/x64/recipes/manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..52956e4ac00166217b36ec5f8ddec16a3f3c11bf
--- /dev/null
+++ b/mac/patchers/desktop/x64/recipes/manifest.json
@@ -0,0 +1,158 @@
+{
+  "schema": "grokbot-desktop-recipes/v1",
+  "files": [
+    {
+      "path": "dist/electron-main/local-browser.cjs",
+      "source": "dist/electron-main/main-app.cjs",
+      "newFile": true,
+      "recipe": "000.gbp.gz",
+      "sha256": "2a447976c74103e3f68b381f53a30c9079a86f65079ea562d63d00826cf22a02",
+      "targetBytes": 2587959,
+      "addedBytes": 252
+    },
+    {
+      "path": "dist/electron-main/local-shared.cjs",
+      "source": "dist/electron-main/main-core.cjs",
+      "newFile": true,
+      "recipe": "001.gbp.gz",
+      "sha256": "0d8462838f249a0c971a91fc3ed08f3a7e31dea1a759f004d1bd823d195819f0",
+      "targetBytes": 856508,
+      "addedBytes": 37
+    },
+    {
+      "path": "dist/electron-preload/preload.cjs",
+      "source": "dist/electron-preload/preload.cjs",
+      "newFile": false,
+      "recipe": "002.gbp.gz",
+      "sha256": "2b1c7128fc4a9674d4dae2a1fdc0dd1676e20ab2bf98513c06a05e0b38d8c66f",
+      "targetBytes": 108285,
+      "addedBytes": 169
+    },
+    {
+      "path": "dist/local-exec-daemon/main.cjs",
+      "source": "dist/local-exec-daemon/main.cjs",
+      "newFile": false,
+      "recipe": "003.gbp.gz",
+      "sha256": "14dae575f4da80612364d3acb3092736f3ba6e63b02363ff6d728d920ab19505",
+      "targetBytes": 3548573,
+      "addedBytes": 142
+    },
+    {
+      "path": "dist/node-agent-coordinator/local-browser.cjs",
+      "source": "dist/node-agent-coordinator/main.cjs",
+      "newFile": true,
+      "recipe": "004.gbp.gz",
+      "sha256": "86a1c7d9c74911b34109d2e863102c6f2fdee81e0b26a74141db4959f3e0f25a",
+      "targetBytes": 893326,
+      "addedBytes": 167
+    },
+    {
+      "path": "dist/renderer/assets/chunk-marketplace-browse-model-BhyIf8FL.js",
+      "source": "dist/renderer/assets/chunk-marketplace-browse-model-BhyIf8FL.js",
+      "newFile": false,
+      "recipe": "005.gbp.gz",
+      "sha256": "6c69c5bc225059ea0903881cdca2b71215198d572e9cee309da7f61373df0d46",
+      "targetBytes": 13023,
+      "addedBytes": 132
+    },
+    {
+      "path": "dist/renderer/assets/chunk-plugin-detail-view-Do8X90gM.js",
+      "source": "dist/renderer/assets/chunk-plugin-detail-view-Do8X90gM.js",
+      "newFile": false,
+      "recipe": "006.gbp.gz",
+      "sha256": "853a34a5f2ddb59c84d5f3a38bdc47c312075802f36c2d802a2b27c292b1b04b",
+      "targetBytes": 52248,
+      "addedBytes": 80
+    },
+    {
+      "path": "dist/renderer/assets/chunk-sentry-sdk-BODYMp25.js",
+      "source": "dist/renderer/assets/chunk-sentry-sdk-BODYMp25.js",
+      "newFile": false,
+      "recipe": "007.gbp.gz",
+      "sha256": "c7d652382238852eb89be56738c88eeadea73bf54aa12dc13d95408308cd6586",
+      "targetBytes": 132,
+      "addedBytes": 132
+    },
+    {
+      "path": "dist/renderer/assets/chunk-team-bot-overview-panel-Ci30rwa3.js",
+      "source": "dist/renderer/assets/chunk-team-bot-overview-panel-Ci30rwa3.js",
+      "newFile": false,
+      "recipe": "008.gbp.gz",
+      "sha256": "cd90e46edfb42471203aec20b7b39a70f5a248906fb722f0d34e394e50bd8997",
+      "targetBytes": 17601,
+      "addedBytes": 110
+    },
+    {
+      "path": "dist/renderer/assets/chunk-view-DycR8MeP.js",
+      "source": "dist/renderer/assets/chunk-view-DycR8MeP.js",
+      "newFile": false,
+      "recipe": "009.gbp.gz",
+      "sha256": "f85277d599abd1acbada161ca13c0e2c81b4e0e7619c5349be61524d01c683ac",
+      "targetBytes": 10131,
+      "addedBytes": 816
+    },
+    {
+      "path": "dist/renderer/assets/chunk-view-D0tNG50W.js",
+      "source": "dist/renderer/assets/chunk-view-D0tNG50W.js",
+      "newFile": false,
+      "recipe": "010.gbp.gz",
+      "sha256": "c83c179f6cd5af0adadd648de107f826f7aa758b0396b5d5b6a975eb6cdb4c08",
+      "targetBytes": 89260,
+      "addedBytes": 18326
+    },
+    {
+      "path": "dist/renderer/assets/chunk-view-Dd3m_azu.js",
+      "source": "dist/renderer/assets/chunk-view-Dd3m_azu.js",
+      "newFile": false,
+      "recipe": "011.gbp.gz",
+      "sha256": "8d9604976ae9feafe03a00e838b61bff7a0f05dea50f9e7c59c8d9d146ea09a1",
+      "targetBytes": 160122,
+      "addedBytes": 132
+    },
+    {
+      "path": "dist/renderer/assets/chunk-view-BKnGna14.js",
+      "source": "dist/renderer/assets/chunk-view-BKnGna14.js",
+      "newFile": false,
+      "recipe": "012.gbp.gz",
+      "sha256": "4df6673824687e3a1a363b34fdac7aa99ed371bccc61544872785f84d333574c",
+      "targetBytes": 80148,
+      "addedBytes": 1042
+    },
+    {
+      "path": "dist/renderer/assets/grok-local-i18n.js",
+      "source": null,
+      "newFile": true,
+      "recipe": "013.gbp.gz",
+      "sha256": "305d9bf3ef451d746810507d63a30ddcac07b1afd3adacdb794afc76c35be513",
+      "targetBytes": 478,
+      "addedBytes": 478
+    },
+    {
+      "path": "dist/renderer/assets/index-DLY0TQjI.js",
+      "source": "dist/renderer/assets/index-DLY0TQjI.js",
+      "newFile": false,
+      "recipe": "014.gbp.gz",
+      "sha256": "ae6ef1c1f8328b0e119b6cc28624b9a4edbd890ddba580ec524436901c1f6cdb",
+      "targetBytes": 2291891,
+      "addedBytes": 2749
+    },
+    {
+      "path": "dist/renderer/assets/index.eager-app-BIotefBk.js",
+      "source": "dist/renderer/assets/index.eager-app-BIotefBk.js",
+      "newFile": false,
+      "recipe": "015.gbp.gz",
+      "sha256": "e59eface5fb2b0d990b6fd8cf65bb7e779cfdf1f6caf1562ddc57a7529bd5a4e",
+      "targetBytes": 1802887,
+      "addedBytes": 1840
+    },
+    {
+      "path": "dist/renderer/index.html",
+      "source": "dist/renderer/index.html",
+      "newFile": false,
+      "recipe": "016.gbp.gz",
+      "sha256": "40879c11f34b8da679b8b8d94ecd0d028cde91da07979cf04b81a63ae37d0b62",
+      "targetBytes": 1643,
+      "addedBytes": 0
+    }
+  ]
+}
diff --git a/mac/patchers/desktop/x64/supported.json b/mac/patchers/desktop/x64/supported.json
new file mode 100644
index 0000000000000000000000000000000000000000..48ac6139e0595fad9da5c702d72264b6ac036bf4
--- /dev/null
+++ b/mac/patchers/desktop/x64/supported.json
@@ -0,0 +1,13 @@
+{
+  "version": "0.71.2",
+  "bundleId": "com.anysphere.sand",
+  "architecture": "x64",
+  "archive": {
+    "url": "https://downloads.cursor.com/grokbot/stable/darwin-x64/0.71.2/Grok_Bot_0.71.2_x64.dmg",
+    "bytes": 156486357,
+    "sha256": "0187b33b8ec21cb7fbaf380d476b57462dc3a5bb512f919ed9b5b0d25718d4aa"
+  },
+  "asarSha256": "05a48b6088fcb89c00b29cce6bbb6b46b377506cd5a394e51285ca12c55c12d2",
+  "frameworkSha256": "4a839a78abda7b18620ccbc1cf25c7cbd1e2eb20f85f5ee7fb35009b9119276b",
+  "preloadSha256": "3996a35e9a1f38b0e6ee2de402064996ad24291518dc4e017280748e33b3be39"
+}
diff --git a/mac/tests/desktop-attachments.test.mjs b/mac/tests/desktop-attachments.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..a322ae25149cb6689d365b5afda9a679d756ff02
--- /dev/null
+++ b/mac/tests/desktop-attachments.test.mjs
@@ -0,0 +1,185 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { createAttachmentUploads } from '../clients/desktop/attachment-uploads.mjs';
+import { createAttachmentHandlers, createAttachmentMediaResolver } from '../clients/desktop/attachments.mjs';
+import { setLocaleSource } from '../clients/desktop/i18n.mjs';
+
+setLocaleSource(() => 'en');
+const chunk = 4 * 1024 * 1024;
+const unexpected = () => { throw new Error('Unexpected Host request for a local draft'); };
+
+async function fixture(t, command = unexpected, onProgress) {
+  const profile = await mkdtemp(path.join(tmpdir(), 'prokbot-attachment-'));
+  t.after(() => rm(profile, { recursive: true, force: true }));
+  const uploads = createAttachmentUploads({ profile, command, onProgress });
+  const staging = path.join(profile, 'attachment-staging');
+  const destination = path.join(profile, 'saved.txt');
+  const errors = [];
+  const attachments = createAttachmentHandlers({ ...uploads, command,
+    chooseDestination: async () => destination, showDownloadError: async () => errors.push('download') });
+  return { ...uploads.handlers, ...attachments, profile, staging, destination, errors };
+}
+
+test('picked and pasted drafts preview and save locally through both native paths and file URLs', async t => {
+  const f = await fixture(t), filename = 'notes.txt';
+  const sourcePath = path.join(f.profile, filename), bytes = Buffer.from('draft, not yet uploaded');
+  await writeFile(sourcePath, bytes);
+  for (const stage of [() => f.stageAttachmentBytes({ filename, bytes }), () => f.stageAttachmentPath({ filename, sourcePath })]) {
+    const staged = await stage();
+    assert.equal(staged.ok, true);
+    const aliases = [staged.path, pathToFileURL(staged.path).href];
+    if (process.platform === 'win32') aliases.push(staged.path.replaceAll('\\', '/'));
+    for (const source of aliases) {
+      assert.deepEqual(await f.readAttachmentText({ path: source }), { kind: 'text', text: bytes.toString(), bytes: bytes.length, truncated: false });
+      assert.deepEqual(await f.readAttachmentBytes({ path: source, maxBytes: 1 }), { kind: 'too-large', size: bytes.length });
+      assert.deepEqual(await f.readAttachmentBytes({ path: source }), { kind: 'bytes', bytes: Uint8Array.from(bytes), size: bytes.length });
+      assert.equal(await f.downloadAttachment({ path: source, suggestedName: filename }), true);
+      assert.deepEqual(await readFile(f.destination), bytes);
+    }
+    await f.discardStagedAttachment({ path: staged.path });
+  }
+  assert.deepEqual(f.errors, []);
+  assert.deepEqual(await readdir(f.staging), []);
+  assert.deepEqual(await readFile(sourcePath), bytes);
+});
+
+test('staging errors do not create a draft or change the picked file', async t => {
+  const f = await fixture(t), filename = 'empty.txt';
+  const sourcePath = path.join(f.profile, filename);
+  await writeFile(sourcePath, '');
+  assert.deepEqual(await f.stageAttachmentBytes({ filename, bytes: Buffer.alloc(0) }), { ok: false, reason: 'empty' });
+  assert.deepEqual(await f.stageAttachmentPath({ filename, sourcePath }), { ok: false, reason: 'empty' });
+  assert.deepEqual(await f.stageAttachmentPath({ filename, sourcePath: path.join(f.profile, 'missing') }), { ok: false, reason: 'failed' });
+  assert.deepEqual(await f.stageAttachmentBytes({ filename, bytes: Buffer.alloc(25 * 1024 * 1024 + 1) }), { ok: false, reason: 'too-large' });
+  assert.deepEqual(await readdir(f.profile), [filename]);
+});
+
+test('staged preview reads only its displayed prefix and never allocates oversized video bytes', async () => {
+  const head = 6 * 1024 * 1024, sizes = { 'note.md': head + 8, 'long.mp4': 200 * 1024 * 1024 };
+  const reads = [];
+  const withStaged = (name, read) => read({ async read(buffer, start, length, offset) {
+    reads.push({ name, length, offset }); buffer.fill(65, start, start + length); return { bytesRead: length };
+  } }, sizes[name]);
+  const f = createAttachmentHandlers({ command: unexpected, withStaged });
+  assert.deepEqual(await f.readAttachmentBytes({ path: 'long.mp4' }), { kind: 'too-large', size: sizes['long.mp4'] });
+  const media = createAttachmentMediaResolver({ command: unexpected, withStaged, nativeImage: {} });
+  await assert.rejects(media({ source: 'long.mp4' }), /too large to preview/i);
+  const text = await f.readAttachmentText({ path: 'note.md' });
+  assert.equal(text.bytes, sizes['note.md']); assert.equal(text.text.length, head); assert.equal(text.truncated, true);
+  const bytes = await f.readAttachmentBytes({ path: 'note.md' });
+  assert.equal(bytes.size, sizes['note.md']); assert.equal(bytes.bytes.length, head);
+  assert.deepEqual(reads, Array.from({ length: 2 }, () => ({ name: 'note.md', length: head, offset: 0 })));
+});
+
+test('slow uploads retain a deadline for each chunk and do not time out while making progress', async t => {
+  let now = 0, elapsed = 70000;
+  const deadlines = [];
+  t.mock.method(AbortSignal, 'timeout', ms => {
+    const controller = new AbortController(); deadlines.push({ end: now + ms, controller }); return controller.signal;
+  });
+  const f = await fixture(t, async (_method, args, signal) => {
+    now += elapsed;
+    for (const deadline of deadlines) if (deadline.end <= now) deadline.controller.abort();
+    signal.throwIfAborted();
+    return args.offset ? { committedPath: '/fixture/video' } : {};
+  });
+  const filename = 'slow.mp4', sourcePath = path.join(f.profile, filename);
+  await writeFile(sourcePath, Buffer.alloc(chunk + 1, 3));
+  const staged = await f.stageAttachmentPath({ filename, sourcePath });
+  const args = { agentId: 'agent-a', paths: [staged.path], filenames: [filename] };
+  assert.deepEqual(await f.commitStagedAttachments(args), ['/fixture/video']);
+  elapsed = 121000;
+  await assert.rejects(f.commitStagedAttachments({ ...args, agentId: 'agent-b' }), { name: 'AbortError' });
+  await f.discardStagedAttachment({ path: staged.path });
+});
+
+test('the same draft has one commit across native path and URL aliases; discard forgets both', async t => {
+  let calls = 0;
+  const f = await fixture(t, async () => ({ committedPath: `/fixture/upload-${++calls}` }));
+  const filename = 'item.txt', staged = await f.stageAttachmentBytes({ filename, bytes: Buffer.from('item') });
+  const url = pathToFileURL(staged.path).href;
+  const commit = source => f.commitStagedAttachments({ agentId: 'agent-a', paths: [source], filenames: [filename] });
+  const [one, two] = await Promise.all([commit(url), commit(staged.path)]);
+  assert.deepEqual(one, two);
+  assert.equal(calls, 1);
+  assert.deepEqual(await commit(url), one);
+  await f.discardStagedAttachment({ path: staged.path });
+  await assert.rejects(commit(url));
+  assert.equal(calls, 1);
+  assert.deepEqual(await readdir(f.staging), []);
+});
+
+test('invalid entries anywhere in a batch reject before uploading any of its drafts', async t => {
+  let calls = 0;
+  const f = await fixture(t, async () => { calls++; return { committedPath: '/fixture/item' }; });
+  const filename = 'item.txt', staged = await f.stageAttachmentBytes({ filename, bytes: Buffer.from('item') });
+  const paths = Array(2); paths[0] = staged.path;
+  const filenames = Array(2); filenames[0] = filename;
+  await assert.rejects(f.commitStagedAttachments({ agentId: 'agent-a', paths, filenames: [filename, filename] }), /Invalid attachment upload/);
+  await assert.rejects(f.commitStagedAttachments({ agentId: 'agent-a', paths: [staged.path, staged.path], filenames }), /Invalid attachment upload/);
+  assert.equal(calls, 0);
+  await f.discardStagedAttachment({ path: staged.path });
+});
+
+test('an unacknowledged final chunk never reports completion and a retry keeps the original bytes', async t => {
+  const bytes = Buffer.alloc(chunk + 23, 65), received = [], progress = [];
+  let acknowledge = false;
+  const f = await fixture(t, async (method, args) => {
+    assert.equal(method, 'uploadAttachmentChunk');
+    const part = Buffer.from(args.bytesBase64, 'base64');
+    received.push({ id: args.uploadId, offset: args.offset, length: part.length });
+    assert.deepEqual(part, bytes.subarray(args.offset, args.offset + part.length));
+    return acknowledge && args.offset + part.length === args.totalSize ? { committedPath: '/fixture/final' } : {};
+  }, value => progress.push(value.fraction));
+  const filename = 'retry.bin', staged = await f.stageAttachmentBytes({ filename, bytes });
+  const args = { agentId: 'agent-a', paths: [staged.path], filenames: [filename], progressKey: 'progress' };
+  await assert.rejects(f.commitStagedAttachments(args));
+  assert.ok(progress.every(fraction => fraction < 1), 'a failed commit must not show 100%');
+  acknowledge = true;
+  assert.deepEqual(await f.commitStagedAttachments(args), ['/fixture/final']);
+  assert.equal(progress.at(-1), 1);
+  assert.deepEqual(received.map(({ offset }) => offset), [0, chunk, 0, chunk]);
+  assert.notEqual(received[0].id, received[2].id);
+  await f.discardStagedAttachment({ path: staged.path });
+  assert.deepEqual(await readdir(f.staging), []);
+});
+
+test('discard cancels an in-flight commit before removing its file, including repeated discard', async t => {
+  let signal;
+  const started = Promise.withResolvers(), reply = Promise.withResolvers();
+  const f = await fixture(t, async (_method, _args, requestSignal) => {
+    signal = requestSignal; started.resolve();
+    signal.addEventListener('abort', () => reply.reject(signal.reason), { once: true });
+    return reply.promise;
+  });
+  const filename = 'draft.txt', staged = await f.stageAttachmentBytes({ filename, bytes: Buffer.from('draft') });
+  const args = { agentId: 'agent-a', paths: [staged.path], filenames: [filename] };
+  const commit = f.commitStagedAttachments(args);
+  const outcome = commit.then(() => 'committed', () => 'cancelled');
+  await started.promise;
+  const discards = [staged.path, pathToFileURL(staged.path).href].map(source => f.discardStagedAttachment({ path: source }));
+  const aborted = signal.aborted;
+  reply.resolve({ committedPath: '/fixture/stale' });
+  await Promise.all(discards);
+  assert.equal(await outcome, 'cancelled');
+  assert.equal(aborted, true);
+  await assert.rejects(f.commitStagedAttachments(args));
+  assert.deepEqual(await readdir(f.staging), []);
+});
+
+test('a remote chunk failure preserves the destination and removes the partial download', async t => {
+  const bytes = Buffer.alloc(chunk, 49);
+  const f = await fixture(t, async (_method, { offset, length }) => {
+    if (offset === chunk) throw new Error('fixture interruption');
+    return { totalSize: chunk + 1, bytesBase64: length ? bytes.toString('base64') : '' };
+  });
+  await writeFile(f.destination, 'previous contents');
+  assert.equal(await f.downloadAttachment({ path: 'file:///fixture/report.txt' }), false);
+  assert.deepEqual(f.errors, ['download']);
+  assert.equal(await readFile(f.destination, 'utf8'), 'previous contents');
+  assert.deepEqual(await readdir(f.profile), [path.basename(f.destination)]);
+});
diff --git a/mac/tests/desktop-dictation.test.mjs b/mac/tests/desktop-dictation.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..e7cb5c87a7056653dc951a673e0f76340548d3d9
--- /dev/null
+++ b/mac/tests/desktop-dictation.test.mjs
@@ -0,0 +1,72 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createDictation, pcmWav } from '../clients/desktop/dictation.mjs';
+
+test('streamed dictation is sent to the Host once as a 16 kHz mono WAV recording', async () => {
+  const requests = [], events = [];
+  const dictation = createDictation({ emit: value => events.push(value),
+    request: async (endpoint, body, signal) => { requests.push({ endpoint, body, signal }); return { text: ' 你好 ', provider: 'fixture' }; } });
+  const { sessionId } = dictation.startDictation({ language: 'zh' });
+  dictation.pushDictationAudio({ sessionId, pcm16: new Uint8Array([1, 0, 2, 0]) });
+  dictation.pushDictationAudio({ sessionId, pcm16: new Uint8Array([3, 0]).buffer });
+  dictation.pushDictationAudio({ sessionId: 'unknown', pcm16: new Uint8Array([9, 9]) });
+  assert.deepEqual(await dictation.stopDictation({ sessionId }), { text: ' 你好 ' });
+  assert.equal(requests.length, 1);
+  const { endpoint, body } = requests[0];
+  assert.equal(endpoint, '/local/audio/transcriptions');
+  assert.equal(body.mimeType, 'audio/wav');
+  assert.equal(body.language, 'zh');
+  const wav = Buffer.from(body.audioBase64, 'base64');
+  assert.equal(wav.toString('ascii', 0, 4), 'RIFF');
+  assert.equal(wav.readUInt16LE(22), 1, 'mono');
+  assert.equal(wav.readUInt32LE(24), 16000);
+  assert.equal(wav.readUInt16LE(34), 16);
+  assert.deepEqual([...wav.subarray(44)], [1, 0, 2, 0, 3, 0]);
+  assert.deepEqual(events, []);
+  assert.deepEqual(await dictation.stopDictation({ sessionId }), { text: '' }, 'a finished session has nothing left');
+});
+
+test('a new, cancelled or silent dictation never reaches the Host and ends the earlier session', async () => {
+  const requests = [], events = [];
+  const dictation = createDictation({ emit: value => events.push(value), request: async () => { requests.push(1); return { text: 'x' }; } });
+  const first = dictation.startDictation();
+  dictation.pushDictationAudio({ sessionId: first.sessionId, pcm16: new Uint8Array([1, 0]) });
+  const second = dictation.startDictation({});
+  assert.notEqual(second.sessionId, first.sessionId);
+  assert.deepEqual(events, [{ sessionId: first.sessionId, isEnded: true }]);
+  assert.deepEqual(await dictation.stopDictation(first), { text: '' });
+  assert.deepEqual(await dictation.stopDictation(second), { text: '' }, 'no audio');
+  const third = dictation.startDictation();
+  dictation.pushDictationAudio({ sessionId: third.sessionId, pcm16: new Uint8Array([1, 0]) });
+  dictation.cancelDictation(third);
+  assert.deepEqual(await dictation.stopDictation(third), { text: '' });
+  assert.equal(requests.length, 0);
+});
+
+test('cancelling while the Host transcribes aborts the request', async () => {
+  let seen;
+  const dictation = createDictation({ emit: () => {}, request: (_endpoint, _body, signal) => {
+    seen = signal;
+    return new Promise((_resolve, reject) => signal.addEventListener('abort', () => reject(signal.reason)));
+  } });
+  const { sessionId } = dictation.startDictation();
+  dictation.pushDictationAudio({ sessionId, pcm16: new Uint8Array([1, 0]) });
+  const pending = dictation.stopDictation({ sessionId });
+  dictation.cancelDictation({ sessionId });
+  await assert.rejects(pending);
+  assert.equal(seen.aborted, true);
+});
+
+test('WAV header sizes follow the PCM length', () => {
+  const wav = pcmWav(new Uint8Array(10), 8000), view = new DataView(wav.buffer);
+  assert.equal(wav.length, 54);
+  assert.equal(view.getUint32(4, true), 46);
+  assert.equal(view.getUint32(28, true), 16000);
+  assert.equal(view.getUint32(40, true), 10);
+});
+
+test('the module needs no Node built-ins, so the Android WebView shares it', async () => {
+  const { readFile } = await import('node:fs/promises');
+  const source = await readFile(new URL('../clients/desktop/dictation.mjs', import.meta.url), 'utf8');
+  assert.doesNotMatch(source, /\bBuffer\b|node:|AbortSignal\.(any|timeout)/);
+});
diff --git a/mac/tests/desktop-download.test.mjs b/mac/tests/desktop-download.test.mjs
index 9028c1b4d873ae08d3f0fe201305f827dcfad58c..424811a8b8c0794944e3263de79aee0b0f530f8b 100644
--- a/mac/tests/desktop-download.test.mjs
+++ b/mac/tests/desktop-download.test.mjs
@@ -54,8 +54,17 @@ test('failed HTTP and fingerprint checks leave no cached input or partial downlo
   assert.equal(f.requests(), 3);
 });
 
-test('an explicit original app or DMG is used without contacting the download server', async () => {
-  for (const source of ['./original.app', './original.dmg']) {
-    assert.equal(await acquireDesktopSource({ source, fetchImpl: () => { throw new Error('Unexpected download'); } }), path.resolve(source));
-  }
+test('an explicit original app is passed to bundle verification without downloading', async () => {
+  assert.equal(await acquireDesktopSource({ source: './original.app', fetchImpl: () => assert.fail('network') }), path.resolve('original.app'));
+});
+
+test('an explicit DMG must match its entire archive pin before it is mounted', async t => {
+  const f = await fixture(t), source = path.join(f.options.cacheDirectory, 'input.DMG');
+  const options = { ...f.options, source, fetchImpl: () => assert.fail('network') };
+  await writeFile(source, body);
+  assert.equal(await acquireDesktopSource(options), source);
+  const damaged = Buffer.from(body); damaged[damaged.length - 1] ^= 1;
+  await writeFile(source, damaged);
+  await assert.rejects(acquireDesktopSource(options), /DMG/);
+  assert.deepEqual(await readFile(source), damaged); assert.equal(f.requests(), 0);
 });
diff --git a/mac/tests/desktop-external-links.test.mjs b/mac/tests/desktop-external-links.test.mjs
index 79cbadf5005e56bb767c890c69db52b9f4ccd47d..59a75b31f576080b34815c07c06400cd03209647 100644
--- a/mac/tests/desktop-external-links.test.mjs
+++ b/mac/tests/desktop-external-links.test.mjs
@@ -52,6 +52,6 @@ test('opens explicit external links through the desktop bridge', async t => {
 
   await call('openExternal', { url: 'https://example.com/' });
   await call('openExternal', { url: 'grokbot-local:agent/example' });
-  await assert.rejects(call('openExternal', { url: 'file:///etc/passwd' }), /Invalid link address/);
+  await assert.rejects(call('openExternal', { url: 'file:///etc/passwd' }), /Invalid link address|链接地址无效/);
   assert.deepEqual(opened, ['https://example.com/']);
 });
diff --git a/mac/tests/desktop-inputs.test.mjs b/mac/tests/desktop-inputs.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..3ee69731754ee9e2bf300b18580a5af53655e34e
--- /dev/null
+++ b/mac/tests/desktop-inputs.test.mjs
@@ -0,0 +1,49 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { open, readFile } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { gunzipSync } from 'node:zlib';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const mac = fileURLToPath(new URL('../', import.meta.url));
+const sha = bytes => createHash('sha256').update(bytes).digest('hex');
+const json = async file => JSON.parse(await readFile(path.join(mac, file), 'utf8'));
+const builds = [
+  { arch: 'arm64', inputs: 'patchers/desktop', tailcat: 'dist/network/grokbot-tailcat', cpu: 0x0100000c, feed: 'darwin-arm64' },
+  { arch: 'x64', inputs: 'patchers/desktop/x64', tailcat: 'dist/network/x64/grokbot-tailcat', cpu: 0x01000007, feed: 'darwin-x64' },
+];
+
+async function machHeader(file) {
+  const handle = await open(path.join(mac, file), 'r');
+  try { const bytes = Buffer.alloc(8); await handle.read(bytes, 0, 8, 0); return bytes; } finally { await handle.close(); }
+}
+
+test('each Mac build has its own pinned original, recipes and Tailcat for its CPU', async () => {
+  for (const build of builds) {
+    const supported = await json(`${build.inputs}/supported.json`);
+    assert.equal(supported.architecture, build.arch);
+    assert.ok(supported.archive.url.includes(`/${build.feed}/${supported.version}/`), build.arch);
+    for (const key of ['asarSha256', 'frameworkSha256', 'preloadSha256']) assert.match(supported[key], /^[0-9a-f]{64}$/);
+    const manifest = await json(`${build.inputs}/recipes/manifest.json`);
+    for (const entry of manifest.files)
+      assert.equal(sha(await readFile(path.join(mac, build.inputs, 'recipes', entry.recipe))), entry.sha256, entry.path);
+    await readFile(path.join(mac, build.inputs, 'notification-policy.json'));
+    const header = await machHeader(build.tailcat);
+    assert.equal(header.readUInt32LE(0), 0xfeedfacf, `${build.tailcat} is not a 64-bit Mach-O`);
+    assert.equal(header.readUInt32LE(4), build.cpu, `${build.tailcat} is built for another CPU`);
+  }
+});
+
+test('the Intel recipes add the same code as the Apple silicon recipes', async () => {
+  const [arm, x64] = await Promise.all(builds.map(build => json(`${build.inputs}/recipes/manifest.json`)));
+  assert.equal(x64.files.length, arm.files.length);
+  // Only the content hashes in renderer asset names differ between the two builds.
+  const mask = text => text.replace(/-[\w-]{8}(\.(?:js|css|svg|png|wav|mp3|webp|woff2?|json|wasm))/g, '-HASHHASH$1');
+  const added = async (inputs, entry) => JSON.parse(gunzipSync(await readFile(path.join(mac, inputs, 'recipes', entry.recipe))))
+    .ops.filter(op => op[0] === 'add').map(op => mask(Buffer.from(op[1], 'base64').toString('utf8')));
+  for (const [index, entry] of arm.files.entries()) {
+    assert.equal(mask(x64.files[index].path), mask(entry.path));
+    assert.deepEqual(await added(builds[1].inputs, x64.files[index]), await added(builds[0].inputs, entry), entry.path);
+  }
+});
diff --git a/mac/tests/desktop-integration.test.mjs b/mac/tests/desktop-integration.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..69b7e5ffd65275d9f8bda4895c2ba3516685fe1e
--- /dev/null
+++ b/mac/tests/desktop-integration.test.mjs
@@ -0,0 +1,68 @@
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import test from 'node:test';
+import * as desktop from '../clients/desktop/platform.mjs';
+
+async function fixture(t) {
+  const dir = await mkdtemp(path.join(tmpdir(), 'prokbot-integration-'));
+  t.after(() => rm(dir, { force: true, recursive: true }));
+  const link = path.join(dir, 'Microsoft', 'Windows', 'Start Menu', 'Programs', desktop.SHORTCUT_NAME);
+  await mkdir(path.dirname(link), { recursive: true });
+  return { dir, link, exe: path.join(dir, 'client.exe'), app: { getPath: () => dir } };
+}
+
+test('startup never replaces an existing shortcut pointing at another program or an unreadable file', async t => {
+  const { dir, link, exe, app } = await fixture(t);
+  await writeFile(link, 'fixture owned by another installation');
+  let writes = 0;
+  for (const readShortcutLink of [() => ({ target: path.join(dir, 'other.exe') }), () => { throw new Error('not a link'); }]) {
+    const shell = { readShortcutLink, writeShortcutLink: () => { writes++; return true; } };
+    assert.equal(desktop.ensureStartMenuShortcut({ app, shell, execPath: exe }), false);
+  }
+  assert.equal(writes, 0);
+});
+
+test('startup creates a missing shortcut and only adds the toast ID to its own existing link', async t => {
+  const { link, exe, app } = await fixture(t);
+  const writes = [], shell = { readShortcutLink: () => ({ target: exe, args: '--existing' }),
+    writeShortcutLink: (...args) => { writes.push(args); if (args[1] === 'create') writeFileSync(args[0], 'test link'); return true; } };
+  assert.equal(desktop.ensureStartMenuShortcut({ app, shell, execPath: exe }), true);
+  assert.equal(writes[0][1], 'create');
+  await writeFile(link, 'existing link');
+  assert.equal(desktop.ensureStartMenuShortcut({ app, shell, execPath: exe }), true);
+  assert.deepEqual(writes[1], [link, 'update', { appUserModelId: desktop.APP_USER_MODEL_ID }]);
+  shell.readShortcutLink = () => ({ target: exe, appUserModelId: desktop.APP_USER_MODEL_ID });
+  assert.equal(desktop.ensureStartMenuShortcut({ app, shell, execPath: exe }), false);
+  assert.equal(writes.length, 2);
+});
+
+test('isolated profiles and Windows side-by-side installations cannot claim OS integration on launch', async t => {
+  const { dir, exe } = await fixture(t);
+  const opts = { execPath: exe, platform: 'win32', isolatedProfile: false };
+  const permit = overrides => desktop.canRegisterDesktopIntegration({ ...opts, ...overrides });
+  assert.equal(await permit({ isolatedProfile: true }), false);
+  assert.equal(await permit({ platform: 'darwin', isolatedProfile: true }), false);
+  assert.equal(await permit({}), true, 'portable install without a receipt');
+  const file = path.join(dir, '.grokbot-installation.json');
+  const receipt = { format: 1, appId: desktop.APP_USER_MODEL_ID, directory: dir };
+  await writeFile(file, JSON.stringify({ ...receipt, sideBySideOf: path.join(dir, 'old') }));
+  assert.equal(await permit({}), false);
+  await writeFile(file, 'invalid');
+  assert.equal(await permit({}), false);
+  await writeFile(file, JSON.stringify({ ...receipt, directory: path.dirname(dir) }));
+  assert.equal(await permit({}), false);
+  await writeFile(file, JSON.stringify(receipt));
+  assert.equal(await permit({}), true);
+});
+
+test('a shortcut created concurrently wins without being overwritten', async t => {
+  const { link, exe, app } = await fixture(t);
+  const shell = { writeShortcutLink(stage) {
+    writeFileSync(stage, 'candidate'); writeFileSync(link, 'user link'); return true;
+  } };
+  assert.equal(desktop.ensureStartMenuShortcut({ app, shell, execPath: exe }), false);
+  assert.equal(readFileSync(link, 'utf8'), 'user link');
+});
diff --git a/mac/tests/desktop-ipc-contract.test.mjs b/mac/tests/desktop-ipc-contract.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..d8ded11a8ca0582e07a55fe8384da17ca7719a3a
--- /dev/null
+++ b/mac/tests/desktop-ipc-contract.test.mjs
@@ -0,0 +1,233 @@
+import assert from 'node:assert/strict';
+import { EventEmitter } from 'node:events';
+import { mkdtemp, rmdir } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { createGateway } from '../clients/desktop/gateway.mjs';
+import { createLocalServices, desktopEdges, probeLocalMethod } from '../clients/desktop/local-services.mjs';
+import { subscribe } from '../clients/desktop/streams.mjs';
+
+const turn = () => new Promise(resolve => setImmediate(resolve));
+const config = { server: 'https://fixture.invalid', token: 'unused-fixture' };
+
+function attach(gateway) {
+  const replies = [];
+  const port = Object.assign(new EventEmitter(), {
+    start() {}, close() { this.emit('close'); }, postMessage(frame) { replies.push(frame); },
+  });
+  const dispose = gateway.attach(port);
+  const send = data => port.emit('message', { data });
+  return { port, replies, dispose, send,
+    request: requestId => send({ kind: 'request', requestId, method: 'listAgents', args: {} }),
+    cancel: requestId => send({ kind: 'cancel', requestId }) };
+}
+
+function delayedFetch(t) {
+  const calls = [];
+  t.mock.method(globalThis, 'fetch', (_url, { signal }) => {
+    const { resolve, promise } = Promise.withResolvers();
+    calls.push({ signal, finish: (value, status = 200) => resolve(Response.json(value, { status })) });
+    return promise; // Deliberately let a response arrive after cancellation.
+  });
+  return calls;
+}
+
+test('desktop IPC probes require a trusted window, a declaration and an installed own handler', async t => {
+  const profile = await mkdtemp(path.join(os.tmpdir(), 'desktop-ipc-fixture-'));
+  t.after(() => rmdir(profile));
+  t.mock.method(console, 'error', () => {});
+  let invoked = 0;
+  const call = await createLocalServices(profile, {}, { settings: { fixtureView: () => ++invoked } });
+  const declared = new Set(['fixtureView', 'unusedDeclaration', 'resolveAttachmentMedia', 'reportFixture', 'toString']);
+  const probe = method => probeLocalMethod(true, declared, call, method);
+  assert.deepEqual(probeLocalMethod(false, declared, call, 'fixtureView'), { ok: false, value: false });
+  assert.deepEqual(probeLocalMethod(true, declared, null, 'fixtureView'), { ok: true, value: false });
+  assert.deepEqual(probe('fixtureView'), { ok: true, value: true });
+  for (const method of ['unusedDeclaration', 'getTimeZone', 'resolveAttachmentMedia', 'reportFixture', 'toString']) {
+    assert.deepEqual(probe(method), { ok: true, value: false }, method);
+  }
+  assert.equal(invoked, 0, 'probing is side-effect free');
+  assert.equal(await call('fixtureView'), 1);
+  await assert.rejects(call('toString'), /does not implement/);
+});
+
+test('desktop edges keep inline panel and Spotlight declarations out of the main edge in either minified style', () => {
+  for (const helper of ['t', 'n']) {
+    const preload = `x=ge("desktop-mount",{methods:{mount:${helper}().args({at:o({x:y()})}),notePointerRegion:${helper}().noArgs},events:te()}),`
+      + `Fc={getThemeState:${helper}().noArgs,mount:${helper}().noArgs},jc={setEnabled:${helper}().args({enabled:y()})};`
+      + `M=ge("main",{methods:{...Fc,...jc}}),S=ge("spotlight",{methods:{readSettings:${helper}().noArgs,setEnabled:${helper}().args({enabled:y()})}});`;
+    const { main, others } = desktopEdges(preload);
+    assert.deepEqual([...main].sort(), ['getThemeState', 'mount', 'setEnabled'], helper);
+    assert.deepEqual([...others].map(([edge, names]) => [edge, [...names]]),
+      [['desktop-mount', ['mount', 'notePointerRegion']], ['spotlight', ['readSettings', 'setEnabled']]], helper);
+  }
+});
+
+test('desktop coordinator deduplicates in-flight IDs per port and cancellation wins over a late success', async t => {
+  const calls = delayedFetch(t);
+  const gateway = createGateway(config);
+  t.after(() => gateway.close());
+  const first = attach(gateway), second = attach(gateway);
+  first.request('same'); first.request('same'); second.request('same');
+  assert.equal(calls.length, 2, 'one Host command per active ID on each port');
+  first.cancel('absent');
+  assert.deepEqual(calls.map(call => call.signal.aborted), [false, false]);
+  first.cancel('same'); first.cancel('same');
+  assert.deepEqual(calls.map(call => call.signal.aborted), [true, false]);
+  calls[1].finish(['second']); calls[0].finish(['stale']);
+  await turn();
+  assert.deepEqual(second.replies, [{ kind: 'reply', requestId: 'same', outcome: { status: 'ok', value: ['second'] } }]);
+  assert.equal(first.replies.length, 1);
+  assert.equal(first.replies[0].requestId, 'same');
+  assert.equal(first.replies[0].outcome.status, 'failed');
+  assert.equal(first.replies[0].outcome.failure.code, 'cancelled');
+  first.request('same');
+  assert.equal(calls.length, 3, 'a settled ID does not block a later request');
+  calls[2].finish(['later']); await turn();
+  assert.deepEqual(first.replies[1].outcome, { status: 'ok', value: ['later'] });
+});
+
+test('1.1.0 global search uses the Host search methods and reports one complete page', async t => {
+  const requests = [];
+  t.mock.method(globalThis, 'fetch', async (url, opts) => {
+    requests.push({ path: new URL(url).pathname, body: JSON.parse(opts.body) });
+    return Response.json([{ agentId: 'a', entryId: 'e' }]);
+  });
+  const gateway = createGateway(config);
+  t.after(() => gateway.close());
+  for (const method of ['searchMessages', 'searchFiles']) {
+    assert.deepEqual(await gateway.command(method, { query: 'q', continuation: 'ignored' }),
+      { matches: [{ agentId: 'a', entryId: 'e' }], coverage: { kind: 'complete' } });
+  }
+  assert.deepEqual(requests, [{ path: '/api/searchAgents', body: { query: 'q' } }, { path: '/api/searchMedia', body: { query: 'q' } }]);
+  assert.equal(await gateway.command('noteTranscriptOpened', { agentId: 'a' }), null);
+  assert.deepEqual(await gateway.command('takeTeachLearningPrompts'), []);
+  assert.equal(requests.length, 2);
+});
+
+test('port and gateway teardown abort outstanding commands without posting stale replies', async t => {
+  const calls = delayedFetch(t);
+  const gateway = createGateway(config);
+  t.after(() => gateway.close());
+  const first = attach(gateway), second = attach(gateway);
+  first.request('a'); first.request('b'); second.request('a');
+  first.port.close(); first.dispose();
+  assert.deepEqual(calls.map(call => call.signal.aborted), [true, true, false]);
+  gateway.close();
+  assert.equal(calls[2].signal.aborted, true);
+  for (const call of calls) call.finish('after close');
+  await turn();
+  assert.deepEqual([...first.replies, ...second.replies], []);
+  assert.equal(first.port.listenerCount('message') + second.port.listenerCount('message'), 0);
+});
+
+test('an explicit incompatible coordinator hello never acknowledges readiness or opens a Host stream', t => {
+  const calls = delayedFetch(t), gw = createGateway(config);
+  t.after(() => gw.close());
+  for (const protocolVersion of [4, null, '3']) {
+    const session = attach(gw);
+    session.send({ kind: 'lifecycle', phase: 'hello', protocolVersion });
+    session.request('after-mismatch');
+    assert.equal(session.port.listenerCount('message'), 0);
+    assert.deepEqual(session.replies, []);
+  }
+  assert.equal(calls.length, 0);
+});
+
+test('a repeated hello never sends a second ready, and renderer shutdown cancels only its own port', async t => {
+  let revoked = 0;
+  const calls = delayedFetch(t), gw = createGateway(config, () => { revoked++; });
+  t.after(() => gw.close());
+  const first = attach(gw), other = attach(gw);
+  const hello = { kind: 'lifecycle', phase: 'hello', protocolVersion: 3 };
+  first.send(hello); first.send(hello); other.send(hello);
+  first.request('work');
+  first.send({ kind: 'lifecycle', phase: 'shutdown', reason: 'requested', detail: null });
+  first.request('after-shutdown');
+  assert.equal(calls.length, 3, 'one stream per port, one legitimate command, no post-shutdown call');
+  assert.deepEqual(calls.map(call => call.signal.aborted), [true, false, true]);
+  calls[2].finish({ error: 'late' }, 401); await turn();
+  assert.equal(revoked, 0, 'an abandoned window must not revoke a live sibling');
+  assert.deepEqual(first.replies, [{ kind: 'lifecycle', phase: 'ready', protocolVersion: 3 }]);
+  assert.deepEqual(other.replies, first.replies);
+});
+
+test('an error page or partial HTTP response cannot make the event transport online', async t => {
+  const mock = t.mock.method(globalThis, 'fetch', () => { throw new Error('missing fixture'); });
+  for (const [status, type] of [[200, 'text/html'], [200, 'text/event-stream-extra'], [200, ''], [206, 'text/event-stream']]) {
+    const control = new AbortController(), stages = [];
+    mock.mock.mockImplementation(async () => new Response(Buffer.from('data: {"fixture":true}\n\n'), { status,
+      headers: type ? { 'Content-Type': type } : {} }));
+    await subscribe(config, '/events', () => stages.push('frame'), control.signal, {
+      onConnected: () => stages.push('online'), onDisconnected: () => { stages.push('down'); control.abort(); },
+    });
+    assert.deepEqual(stages, ['down'], `${status} ${type || '(no SSE type)'}`);
+  }
+});
+
+test('baseline hello opens one event stream, forwards its payload, and a revoked device cannot use the port', async t => {
+  let revoked = 0;
+  const gw = createGateway(config, () => { revoked++; });
+  let streamControl;
+  const port = attach(gw), stream = new ReadableStream({ start(s) {
+    streamControl = s;
+    s.enqueue(Buffer.from('id: one\ndata: {"channel":"fixture","payload":{"visible":true}}\n\n'));
+  } });
+  t.after(() => { gw.close(); streamControl.close(); });
+  const requests = [];
+  t.mock.method(globalThis, 'fetch', async (url, opts) => {
+    requests.push({ url, redirect: opts.redirect, authenticated: opts.headers.Authorization === `Bearer ${config.token}` });
+    if (url.endsWith('/events')) return new Response(stream, { headers: { 'Content-Type': 'Text/Event-Stream; charset=utf-8' } });
+    return Response.json({ error: 'revoked' }, { status: 401 });
+  });
+  port.send({ kind: 'lifecycle', phase: 'hello' });
+  port.send({ kind: 'lifecycle', phase: 'hello', protocolVersion: 3 });
+  await turn();
+  assert.deepEqual(port.replies.filter(f => f.phase === 'ready').map(f => f.protocolVersion), [3]);
+  assert.deepEqual(port.replies.filter(f => f.family === 'fixture').map(f => f.payload), [{ visible: true }]);
+  assert.equal(gw.getState(), 'online');
+  port.request('unauthorized'); for (let i = 0; i < 5; i++) await turn();
+  port.request('after-close'); await turn();
+  assert.equal(revoked, 1);
+  assert.equal(gw.getState(), 'disconnected');
+  assert.equal(port.replies.some(f => f.requestId === 'unauthorized'), false);
+  assert.deepEqual(requests.map(r => r.url),
+    [`${config.server}/events`, `${config.server}/api/listAgents`, `${config.server}/connect/status`]);
+  assert.ok(requests.every(r => r.authenticated && r.redirect === 'error'));
+});
+
+test('a 401 from a Host feature fails only that request while the device is still accepted', async t => {
+  let revoked = 0;
+  const gw = createGateway(config, () => { revoked++; });
+  t.after(() => gw.close());
+  const urls = [];
+  t.mock.method(globalThis, 'fetch', async url => {
+    urls.push(url);
+    if (url.endsWith('/connect/status')) return Response.json({ deviceId: 'fixture' });
+    return Response.json({ error: '连接器授权已过期,请重新授权' }, { status: 401 });
+  });
+  const port = attach(gw);
+  port.request('connector'); port.request('second-connector');
+  for (let i = 0; i < 6; i++) await turn();
+  assert.equal(revoked, 0);
+  assert.notEqual(gw.getState(), 'disconnected');
+  const failures = port.replies.filter(f => f.kind === 'reply').map(f => f.outcome.failure);
+  assert.deepEqual(failures.map(f => [f.httpStatus, f.message]), [[401, '连接器授权已过期,请重新授权'], [401, '连接器授权已过期,请重新授权']]);
+  assert.equal(urls.filter(url => url.endsWith('/connect/status')).length, 1, 'concurrent 401s share one device check');
+  port.request('later'); for (let i = 0; i < 6; i++) await turn();
+  assert.equal(port.replies.filter(f => f.kind === 'reply').length, 3, 'the gateway keeps serving requests');
+});
+
+test('a Host without the device status endpoint gets the original prompt to pair again', async t => {
+  let prompted = 0;
+  const gw = createGateway(config, () => { prompted++; });
+  t.after(() => gw.close());
+  t.mock.method(globalThis, 'fetch', async url => url.endsWith('/connect/status')
+    ? new Response('not found', { status: 404 }) : Response.json({ error: 'unauthorized' }, { status: 401 }));
+  const port = attach(gw);
+  port.request('legacy'); for (let i = 0; i < 6; i++) await turn();
+  assert.equal(prompted, 1);
+  assert.notEqual(gw.getState(), 'disconnected');
+  assert.equal(port.replies.find(f => f.requestId === 'legacy')?.outcome.failure.httpStatus, 401);
+});
diff --git a/mac/tests/desktop-pairing.test.mjs b/mac/tests/desktop-pairing.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..ab3d72ed92d6fa4a3150842c9f4856c8ba144603
--- /dev/null
+++ b/mac/tests/desktop-pairing.test.mjs
@@ -0,0 +1,192 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import * as connection from '../clients/desktop/connection.mjs';
+import { setLocaleSource } from '../clients/desktop/i18n.mjs';
+
+setLocaleSource(() => 'en');
+const server = 'https://fixture.invalid', deviceId = 'fixture-device', token = 'fixture-only-token'.repeat(2);
+const record = { server, deviceId, token };
+const reply = (extra = {}) => Response.json({ deviceId, token, gatewayUrl: server, ...extra }, { status: 201 });
+const key = 'ABC234';
+
+test('pairing normalizes a formatted full-width code and refuses malformed codes before contacting the Host', async () => {
+  const requests = [];
+  const fetcher = async (url, options) => { requests.push({ url, options }); return reply(); };
+  assert.deepEqual(await connection.pair(server, '\uff41\uff42\uff43-\uff12\uff13\uff14', fetcher), record);
+  assert.equal(requests.length, 1);
+  const { url, options } = requests[0];
+  assert.equal(url, `${server}/connect/pair`);
+  assert.equal(options.redirect, 'error');
+  assert.equal(JSON.parse(options.body).platform, 'desktop');
+  assert.equal(JSON.parse(options.body).pairingKey, key);
+  for (const invalid of ['', '12', 'ABCDEFG', 'ABC/23', null]) await assert.rejects(connection.pair(server, invalid, fetcher));
+  assert.equal(requests.length, 1, 'invalid input should not spend a rate-limited Host attempt');
+});
+
+test('pairing preserves HTTP errors and rejects unusable device identities and wrong direct origins', async () => {
+  await assert.rejects(connection.pair(server, key, async () => new Response('expired', { status: 401 })), /expired/i);
+  await assert.rejects(connection.pair(server, key, async () => new Response('unavailable', { status: 503 })), /503/);
+  for (const bad of [null, { deviceId: 42 }, { deviceId: ' ' }, { token: ' '.repeat(18) }]) {
+    await assert.rejects(connection.pair(server, key, async () => bad ? reply(bad) : Response.json(null)), /invalid device credentials/i);
+  }
+  const different = { gatewayUrl: 'https://other-fixture.invalid' };
+  await assert.rejects(connection.pair(server, key, async () => reply(different)), /different server address/i);
+  assert.deepEqual(await connection.pair(server, key, async () => reply(different), { tunneled: true }), record);
+});
+
+async function formFixture(t, state, disconnect = async () => {}) {
+  class Field extends EventTarget { value = ''; style = {}; }
+  const fields = new Map(), requests = [];
+  const document = { documentElement: {}, querySelector(id) {
+    if (!fields.has(id)) fields.set(id, new Field());
+    return fields.get(id);
+  } };
+  const window = { connection: { locale: 'en', status: async () => state, disconnect,
+    pair: async (address, code, tailcat, edit) => { requests.push({ address, code, tailcat, edit }); return { ok: true }; } } };
+  Object.assign(globalThis, { document, window });
+  t.after(() => { delete globalThis.window; delete globalThis.document; });
+  await import(`../clients/desktop/connect.js?fixture=${encodeURIComponent(t.name)}`);
+  await new Promise(resolve => setImmediate(resolve));
+  return { fields, requests, submit: async () => {
+    fields.get('#form').dispatchEvent(new Event('submit', { cancelable: true }));
+    await new Promise(resolve => setImmediate(resolve));
+  } };
+}
+
+test('pairing form preserves an active IME composition and submits the entire normalized paste', async t => {
+  const { fields, requests, submit } = await formFixture(t, {});
+  const field = fields.get('#key');
+  const paste = '\uff41\uff42\uff43-\uff12\uff13\uff14';
+  const html = await readFile(new URL('../clients/desktop/connect.html', import.meta.url), 'utf8');
+  const maxLength = /]*maxlength="(\d+)"/.exec(html)?.[1];
+  field.value = paste.slice(0, Number(maxLength ?? Infinity));
+  field.dispatchEvent(Object.assign(new Event('input'), { isComposing: true }));
+  assert.equal(field.value, paste);
+  field.dispatchEvent(new Event('compositionend'));
+  assert.equal(field.value, key);
+  fields.get('#server').value = server;
+  await submit();
+  assert.deepEqual(requests, [{ address: server, code: key, tailcat: false, edit: false }]);
+});
+
+test('the pairing window can retry a saved transport without a new code or explicitly forget it', async t => {
+  let fail = true;
+  const { fields, requests, submit } = await formFixture(t, { paired: true, connected: false, server, tailcat: true, error: 'offline' }, async () => {
+    if (fail) throw new Error('fixture clear failed');
+  });
+  assert.equal(fields.get('#disconnect').hidden, false);
+  assert.equal(fields.get('#key').required, false);
+  fields.get('#server').value = 'https://changed-fixture.invalid';
+  fields.get('#server').dispatchEvent(new Event('input'));
+  assert.equal(fields.get('#key').required, true, 'automatic reuse is only for the saved address and transport');
+  fields.get('#server').value = server;
+  fields.get('#server').dispatchEvent(new Event('input'));
+  await submit();
+  assert.deepEqual(requests, [{ address: server, code: '', tailcat: true, edit: true }]);
+  fields.get('#key').value = key;
+  await submit();
+  assert.equal(requests[1].edit, false, 'an explicit new code performs a fresh pairing');
+  fields.get('#disconnect').dispatchEvent(new Event('click')); await new Promise(resolve => setImmediate(resolve));
+  assert.equal(fields.get('#status').textContent, 'fixture clear failed');
+  assert.equal(fields.get('#disconnect').hidden, false);
+  fail = false;
+  fields.get('#disconnect').dispatchEvent(new Event('click')); await new Promise(resolve => setImmediate(resolve));
+  assert.equal(fields.get('#disconnect').hidden, true);
+  assert.equal(fields.get('#key').required, true);
+});
+
+test('a saved device may retry its original origin or tunnel, never a different Host or transport', () => {
+  assert.equal(connection.savedConnectionMatches(null, server, false), false);
+  assert.equal(connection.savedConnectionMatches(record, `${server.toUpperCase()}:443/`, false), true);
+  for (const address of ['http://fixture.invalid', 'https://other-fixture.invalid', `${server}:8443`, `${server}/other`, 'invalid']) {
+    assert.equal(connection.savedConnectionMatches(record, address, false), false);
+  }
+  const link = `tc${'a'.repeat(32)}`;
+  const tunnel = { ...record, tailcat: true, address: `tailcat://connect/${link}?port=8000` };
+  assert.equal(connection.savedConnectionMatches(tunnel, link, true), true);
+  assert.equal(connection.savedConnectionMatches(tunnel, `${link}b`, true), false);
+  assert.equal(connection.savedConnectionMatches(tunnel, `tailcat://connect/${link}?port=8001`, true), false);
+  assert.equal(connection.savedConnectionMatches(tunnel, server, false), false);
+  assert.equal(connection.savedConnectionMatches(record, link, true), false);
+});
+
+test('editing a saved connection requires a status response for the same paired device', async () => {
+  const status = value => connection.verifyDevice(server, record, async (url, options) => {
+    assert.equal(url, `${server}/connect/status`);
+    assert.equal(options.headers.authorization, `Bearer ${token}`);
+    assert.equal(options.redirect, 'error');
+    return value;
+  });
+  await status(Response.json({ deviceId }));
+  for (const response of [Response.json({ deviceId: 'another-device' }), Response.json({}), new Response('proxy landing page'), new Response(null, { status: 401 })]) {
+    await assert.rejects(status(response), /verify this device/i);
+  }
+});
+
+test('only healthy workspace startup dismisses its original pairing window, never a revocation prompt', () => {
+  let closed = 0;
+  const pairing = { close() { closed++; } }, recovery = { close: () => assert.fail('closed the new recovery prompt') };
+  connection.finishPairingWindow(pairing, pairing, 'fixture revoked');
+  connection.finishPairingWindow(pairing, recovery, '');
+  connection.finishPairingWindow(null, recovery, '');
+  assert.equal(closed, 0);
+  connection.finishPairingWindow(pairing, pairing, '');
+  assert.equal(closed, 1);
+});
+
+test('failed tunnel startup keeps the saved device for retry but does not select a workspace transport', async () => {
+  const saved = { ...record, server: '', address: 'synthetic-tunnel', tailcat: true, networkIdentity: 'synthetic-identity' };
+  const store = { load: async () => saved };
+  const binary = 'fixture-helper';
+  const unavailable = await connection.restoreConnection(store, binary, async () => { throw new Error('fixture tunnel offline'); });
+  assert.equal(unavailable.config, saved);
+  assert.equal(unavailable.transport, null);
+  assert.match(unavailable.connectionError, /reconnect/i);
+  const recovered = await connection.restoreConnection(store, binary, async (address, enabled, options) => {
+    assert.equal(address, saved.address); assert.equal(enabled, true);
+    assert.deepEqual(options, { identity: saved.networkIdentity, binary });
+    return { server, close() {} };
+  });
+  assert.equal(recovered.config.deviceId, deviceId); assert.equal(recovered.config.token, token);
+  assert.equal(recovered.config.server, server); assert.equal(recovered.transport.server, server);
+  assert.equal(recovered.connectionError, '');
+});
+
+test('concurrent credential changes persist in invocation order and logout cannot resurrect an old pairing', async t => {
+  const profile = await mkdtemp(path.join(tmpdir(), 'prokbot-pair-'));
+  t.after(() => rm(profile, { recursive: true, force: true }));
+  const storage = { isEncryptionAvailable: () => true, encryptString: s => Buffer.from(s), decryptString: b => b.toString() };
+  const store = connection.credentialStore(profile, storage);
+  assert.equal(await store.load(), null);
+  const writes = Array.from({ length: 16 }, (_, i) => store.save({ ...record, deviceId: `fixture-${i}` }));
+  const results = await Promise.allSettled(writes);
+  assert.ok(results.every(result => result.status === 'fulfilled'), 'pairing writes must not race over the same temporary file');
+  assert.equal((await store.load()).deviceId, 'fixture-15');
+  await Promise.all([store.save(record), store.clear()]);
+  assert.equal(await store.load(), null);
+  assert.deepEqual(await readdir(profile), []);
+});
+
+test('unusable saved credentials do not activate a workspace and a failed replacement preserves the existing device', async t => {
+  const profile = await mkdtemp(path.join(tmpdir(), 'prokbot-credential-'));
+  t.after(() => rm(profile, { recursive: true, force: true }));
+  let available = true;
+  const storage = { isEncryptionAvailable: () => available, encryptString: s => Buffer.from(s), decryptString: b => b.toString() };
+  const store = connection.credentialStore(profile, storage);
+  await store.save(record);
+  available = false;
+  await assert.rejects(store.save({ ...record, deviceId: 'different' }));
+  available = true;
+  assert.equal((await connection.credentialStore(profile, storage).load()).deviceId, record.deviceId);
+  const file = path.join(profile, 'connection.json');
+  const saved = JSON.parse(await readFile(file, 'utf8'));
+  for (const damaged of [{ deviceId: null }, { encryptedToken: '' }]) {
+    await writeFile(file, JSON.stringify({ ...saved, ...damaged }));
+    await assert.rejects(store.load(), /device credentials/i);
+  }
+  await store.save(record);
+  assert.equal((await store.load()).token, token);
+});
diff --git a/mac/tests/desktop-profile-persistence.test.mjs b/mac/tests/desktop-profile-persistence.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..3e07a100a24eb9039cf05cb3e214e0866fd1b575
--- /dev/null
+++ b/mac/tests/desktop-profile-persistence.test.mjs
@@ -0,0 +1,67 @@
+import assert from 'node:assert/strict';
+import { mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { createLocalServices } from '../clients/desktop/local-services.mjs';
+
+async function fixture(t) {
+  const profile = await mkdtemp(path.join(tmpdir(), 'plus-profile-'));
+  t.after(() => rm(profile, { recursive: true, force: true }));
+  return { profile, file: path.join(profile, 'local-client-persistence.json') };
+}
+
+test('a damaged desktop profile is kept under another name and the client continues with empty data', async t => {
+  const { profile, file } = await fixture(t);
+  t.mock.method(console, 'warn', () => {});
+  for (const original of ['{"saved":', '[]', 'null', '']) {
+    await writeFile(file, original);
+    const call = await createLocalServices(profile, {}, {});
+    assert.equal(await call('readClientPersistence', { key: 'saved' }), null);
+    await call('writeClientPersistence', { key: 'new', value: '1' });
+    assert.equal(await call('readClientPersistence', { key: 'new' }), '1');
+    const kept = (await readdir(profile)).filter(name => name.startsWith(`${path.basename(file)}.damaged-`));
+    assert.equal(kept.length, 1);
+    assert.equal(await readFile(path.join(profile, kept[0]), 'utf8'), original);
+    assert.deepEqual(JSON.parse(await readFile(file, 'utf8')), { new: '1' });
+    await rm(path.join(profile, kept[0]));
+  }
+});
+
+test('a profile that cannot be read is preserved and reported, not replaced', async t => {
+  const { profile, file } = await fixture(t);
+  await mkdir(file);
+  const call = await createLocalServices(profile, {}, {});
+  await assert.rejects(call('writeClientPersistence', { key: 'new', value: '1' }), /profile|设置/i);
+  await assert.rejects(call('readClientPersistence', { key: 'new' }), /profile|设置/i);
+  assert.deepEqual(await readdir(profile), [path.basename(file)]);
+  assert.deepEqual(await readdir(file), []);
+});
+
+test('a failed profile save is not visible in memory or on a later successful save', async t => {
+  const { profile, file } = await fixture(t);
+  await writeFile(file, JSON.stringify({ kept: 'old' }));
+  const call = await createLocalServices(profile, {}, {});
+  assert.equal(await call('readClientPersistence', { key: 'kept' }), 'old');
+  const saved = path.join(profile, 'saved');
+  await rename(file, saved); await mkdir(file);
+  await assert.rejects(call('writeClientPersistence', { key: 'phantom', value: 'never committed' }));
+  assert.equal(await call('readClientPersistence', { key: 'phantom' }), null);
+  await rmdir(file); await rename(saved, file);
+  const writes = Array.from({ length: 12 }, (_, i) => call('writeClientPersistence', { key: `slot${i}`, value: i }));
+  await Promise.all(writes);
+  const reopened = await createLocalServices(profile, {}, {});
+  const all = await reopened('readManyClientPersistence', { include: [''] });
+  assert.deepEqual(all, { kept: 'old', ...Object.fromEntries(writes.map((_, i) => [`slot${i}`, i])) });
+  assert.deepEqual(await readdir(profile), [path.basename(file)]);
+});
+
+test('the desktop about dialog reports the running application, not a hard-coded vendor release', async t => {
+  const { profile } = await fixture(t);
+  for (const appVersion of ['0.71.2', '9.4.2']) {
+    const call = await createLocalServices(profile, {}, { appVersion });
+    const status = await call('getUpdateStatus');
+    assert.equal(status.currentVersion, appVersion);
+    assert.equal(status.state.type, 'disabled');
+  }
+});
diff --git a/mac/tests/desktop-reconnect.test.mjs b/mac/tests/desktop-reconnect.test.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..8e20958911da031d937261c00f7e658bf355c7d6
--- /dev/null
+++ b/mac/tests/desktop-reconnect.test.mjs
@@ -0,0 +1,162 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { EventEmitter, getEventListeners, setMaxListeners } from 'node:events';
+import { createServer } from 'node:http';
+import { syncBuiltinESMExports } from 'node:module';
+import { setTimeout as delay } from 'node:timers/promises';
+import { createGateway } from '../clients/desktop/gateway.mjs';
+import { subscribe } from '../clients/desktop/streams.mjs';
+
+const turn = () => new Promise(resolve => setImmediate(resolve));
+const config = { server: 'https://fixture.invalid', token: 'fixture-device-token' };
+const frame = n => `id: ${n}\r\ndata: {"channel":"fixture","payload":${n}}\r\n\r\n`;
+const eventStream = { headers: { 'Content-Type': 'text/event-stream' } };
+
+test('512 immediately ended SSE connections back off, keep their cursor, and recover quickly after a stable session', async t => {
+  t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 0 });
+  syncBuiltinESMExports();
+  t.mock.method(performance, 'now', () => Date.now());
+  const attempts = [], received = [], controller = new AbortController();
+  setMaxListeners(600, controller.signal);
+  let held;
+  t.mock.method(globalThis, 'fetch', async (_url, options) => {
+    const n = attempts.push({ time: Date.now(), cursor: options.headers['Last-Event-ID'] });
+    return new Response(new ReadableStream({ start(stream) {
+      stream.enqueue(Buffer.from(frame(n)));
+      if (n === 513) held = stream;
+      else stream.close();
+    } }), eventStream);
+  });
+  const run = subscribe(config, '/events', ({ data }) => received.push(data.payload), controller.signal);
+  t.after(async () => { controller.abort(); held?.close(); await run; t.mock.timers.reset(); syncBuiltinESMExports(); });
+  await turn();
+  for (let i = 0; i < 512; i++) {
+    const backoff = Math.min(500 * 2 ** Math.min(i, 5), 10000);
+    t.mock.timers.tick(backoff - 1); await turn();
+    assert.equal(attempts.length, i + 1, `retried early after stream ${i + 1}`);
+    t.mock.timers.tick(1); await turn();
+    assert.equal(attempts.length, i + 2, `missing reconnect after stream ${i + 1}`);
+    assert.equal(attempts[i + 1].cursor, String(i + 1));
+    // Mocked timers/promises retains one abort listener per wait; allow only that harness overhead.
+    const listenerCount = getEventListeners(controller.signal, 'abort').length;
+    assert.ok(listenerCount <= i + 2, 'the live attempt or retry must be the only unbounded listener');
+  }
+  assert.ok(Date.now() > 3600_000, 'more than one virtual hour of disconnects');
+  t.mock.timers.tick(60000);
+  held.close(); held = null; await turn();
+  t.mock.timers.tick(499); await turn(); assert.equal(attempts.length, 513);
+  t.mock.timers.tick(1); await turn(); assert.equal(attempts.length, 514);
+  controller.abort(); await run;
+  t.mock.timers.tick(120000); await turn();
+  assert.deepEqual(received, Array.from({ length: 514 }, (_, i) => i + 1));
+  assert.equal(getEventListeners(controller.signal, 'abort').length, 0);
+});
+
+test('session teardown stops delivery of already buffered frames and ignores a late unauthorized response', async t => {
+  const controller = new AbortController(), received = [];
+  const mock = t.mock.method(globalThis, 'fetch', async () => new Response(frame(1) + frame(2), eventStream));
+  await subscribe(config, '/events', ({ data }) => { received.push(data.payload); controller.abort(); }, controller.signal);
+  assert.deepEqual(received, [1]);
+  const late = Promise.withResolvers(), stopped = new AbortController();
+  let unauthorized = 0;
+  mock.mock.mockImplementation(() => late.promise);
+  const run = subscribe(config, '/events', () => {}, stopped.signal, { onUnauthorized: () => unauthorized++ });
+  stopped.abort(); late.resolve(new Response(null, { status: 401 })); await run;
+  assert.equal(unauthorized, 0);
+});
+
+test('gateway reconnects real loopback SSE, ignores incomplete frames, resets an empty event ID and stops on 401', { timeout: 7000 }, async t => {
+  const cursors = [], messages = [], states = [];
+  const revoked = Promise.withResolvers();
+  const server = createServer((req, res) => {
+    if (req.url !== '/events') {
+      if (req.url === '/api/empty') res.writeHead(204).end();
+      else if (req.url === '/api/malformed') res.writeHead(200).end('not json');
+      else res.writeHead(503, { 'Content-Type': 'text/plain' }).end('fixture interruption');
+      return;
+    }
+    const attempt = cursors.push(req.headers['last-event-id']);
+    if (attempt > 2) { res.writeHead(401).end(); return; }
+    res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+    if (attempt === 1) {
+      res.write(frame(1)); res.end('id: unfinished\ndata: {');
+    } else res.end(': heartbeat\n\nid:\ndata: {"channel":"fixture","payload":2}\n\n');
+  });
+  server.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
+  const gateway = createGateway({ ...config, server: `http://127.0.0.1:${server.address().port}` }, revoked.resolve, undefined, state => states.push(state));
+  let portClosures = 0;
+  const port = Object.assign(new EventEmitter(), { start() {}, close() { portClosures++; }, postMessage(value) { messages.push(value); } });
+  const detach = gateway.attach(port);
+  t.after(async () => { gateway.close(); detach(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });
+  await assert.rejects(gateway.command('uploadAttachmentChunk'), { httpStatus: 503, message: 'HTTP 503' });
+  assert.equal(await gateway.command('empty'), null);
+  await assert.rejects(gateway.command('malformed'), SyntaxError);
+  for (let i = 0; i < 2; i++) port.emit('message', { data: { kind: 'lifecycle', phase: 'hello' } });
+  await revoked.promise;
+  assert.deepEqual(cursors, [undefined, '1', undefined]);
+  assert.deepEqual(messages.filter(m => m.family === 'fixture').map(m => m.payload), [1, 2]);
+  assert.deepEqual(messages.filter(m => m.family === 'transport-connected').map(m => m.payload.generation), [1, 2]);
+  assert.deepEqual(messages.filter(m => m.family === 'coordinator-transport-state').map(m => m.payload.state),
+    ['connected', 'down', 'connected', 'down'], 'the renderer sees connection loss and recovery');
+  assert.equal(messages.filter(m => m.kind === 'lifecycle' && m.phase === 'ready').length, 1);
+  assert.deepEqual(states.slice(0, 4), ['online', 'reconnecting', 'online', 'reconnecting']);
+  assert.equal(gateway.getState(), 'disconnected', 'a revoked subscription will not retry');
+  assert.equal(portClosures, 1, 'the renderer must not keep a dead port with pending calls');
+  await assert.rejects(gateway.command('empty'), /Disconnected|已退出/);
+  gateway.close(); detach();
+  assert.equal(portClosures, 1);
+  assert.equal(gateway.getState(), 'disconnected');
+  assert.equal(port.listenerCount('message'), 0);
+});
+
+// Opt-in real-time run; the deterministic 512-connection test stays in ordinary CI.
+if (process.env.PROKBOT_DESKTOP_SOAK_SECONDS) {
+  const seconds = Number(process.env.PROKBOT_DESKTOP_SOAK_SECONDS);
+  assert.ok(Number.isSafeInteger(seconds) && seconds >= 60 && seconds <= 86400);
+  test('wall-clock loopback session soak with short streams, stable streams and concurrent commands', { timeout: (seconds + 15) * 1000 }, async t => {
+    let connections = 0, delivered = 0, requests = 0, gaps = 0, badCursors = 0, openStreams = 0, peakStreams = 0;
+    const server = createServer(async (req, res) => {
+      if (req.url === '/api/echo') {
+        const parts = [];
+        for await (const part of req) parts.push(part);
+        res.writeHead(200, { 'Content-Type': 'application/json' }).end(Buffer.concat(parts)); return;
+      }
+      if (req.url !== '/events') { res.writeHead(404).end(); return; }
+      let cursor = Number(req.headers['last-event-id'] ?? 0);
+      if (cursor !== delivered) badCursors++;
+      const attempt = ++connections;
+      peakStreams = Math.max(peakStreams, ++openStreams);
+      res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+      const send = () => res.write(frame(++cursor));
+      send();
+      const interval = setInterval(send, 100);
+      const end = setTimeout(() => res.end('id: partial\ndata: {'), attempt % 8 === 4 ? 35000 : 40);
+      res.once('close', () => { clearInterval(interval); clearTimeout(end); openStreams--; });
+    });
+    server.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
+    const gateway = createGateway({ ...config, server: `http://127.0.0.1:${server.address().port}` });
+    const port = Object.assign(new EventEmitter(), { start() {}, close() {}, postMessage(message) {
+      if (message.family !== 'fixture') return;
+      if (message.payload !== delivered + 1) gaps++;
+      delivered = message.payload;
+    } });
+    const detach = gateway.attach(port);
+    t.after(async () => { gateway.close(); detach(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });
+    const start = performance.now(), until = start + seconds * 1000;
+    port.emit('message', { data: { kind: 'lifecycle', phase: 'hello' } });
+    while (performance.now() < until) {
+      const args = { request: ++requests };
+      assert.deepEqual(await gateway.command('echo', args, AbortSignal.timeout(5000)), args);
+      await delay(Math.min(1000, Math.max(0, until - performance.now())));
+    }
+    detach(); gateway.close();
+    const stoppedAt = delivered;
+    await delay(550);
+    assert.equal(delivered, stoppedAt);
+    assert.equal(gateway.getState(), 'disconnected');
+    assert.equal(openStreams, 0); assert.equal(peakStreams, 1);
+    assert.equal(gaps, 0); assert.equal(badCursors, 0);
+    assert.ok(connections >= 6 && delivered >= 100 && requests >= seconds / 2);
+    t.diagnostic(JSON.stringify({ wallSeconds: (performance.now() - start) / 1000, connections, delivered, requests, gaps, badCursors, peakStreams, openStreams }));
+  });
+}